Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Last active October 31, 2024 14:50
Show Gist options
  • Save peteristhegreat/ac8a4f1e7c350d44f49be669fc41a358 to your computer and use it in GitHub Desktop.
Save peteristhegreat/ac8a4f1e7c350d44f49be669fc41a358 to your computer and use it in GitHub Desktop.
Read a char* from a dll in vba
Option Explicit
Declare PtrSafe Function lstrlenA Lib "kernel32" (ByVal lpString As LongPtr) As Long
Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
ByVal Destination As String, ByVal Source As LongPtr, ByVal length As Long)
Private Declare PtrSafe Function api_get_message Lib "C:\tools\my-api\bin\mydll.dll" () As LongPtr
Function PtrToStringAnsi(ByVal lpString As LongPtr) As String
Dim length As Long
length = lstrlenA(lpString) ' Get the length of the string
If length > 0 Then
PtrToStringAnsi = String(length, vbNullChar) ' Allocate space
CopyMemory PtrToStringAnsi, lpString, length ' Copy the memory
End If
End Function
Public Function API_GetMessage() As String
Dim messagePtr As LongPtr
Dim message As String
messagePtr = api_get_message()
If messagePtr <> 0 Then
message = PtrToStringAnsi(messagePtr)
message = Replace(message, "\n", vbNewLine)
API_GetMessage = message
Else
API_GetMessage = "No message available."
End If
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment