Passing String Arguments to DLL Functions

Strings that are passing into a DLL function or that are returned by a DLL function are treated by default as Unicode Strings. If your DLL function requires ANSI String arguments, use the CharacterSet property of the DllFunctionOptions attribute.

Example

<Dll( "user32.dll" )> Public Interface IUserDll32Functions
  <DllFunctionOptions(CharacterSet:=CharacterSet.Ansi)> Function SendMessageA( _
    ByVal obj As TestObject, ByVal message As Integer , ByVal wParam As Integer , ByRef lParam As String ) As Integer
End Interface

Passing a String back from a DLL call as a ByRef argument works per default if the String's size does not exceed 256 characters length. If the String that should be passed back is longer than 256 characters, you need to pass a Visual Basic String in that is long enough to hold the resulting String.

Example

Use the following code to create a String with 1024 blank characters:
Dim longEmptyString = New String ( " "c , 1024 )
Pass this String as a ByRef argument into a DLL function and the DLL function will pass back Strings of up to 1024 characters of length.

When passing a String back from a DLL call as a function return value, the DLL should implement a DLL function called FreeDllMemory that accepts the C String pointer returned by the DLL function and that frees the previously allocated memory. If no such function exists the memory will be leaked.