How do I import and call unmanaged C dll with ansi string "char *" pointer string from VB.net?
- by Warren P
I have written my own function, which in C would be declared like this, using standard Win32 calling conventions:
int Thing( char * command, char * buffer, int * BufSize);
I have the following amount of VB figured out, which should import the dll and call this function, wrapping it up to make it easy to call Thing("CommandHere",GetDataBackHere):
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices
Imports System
Imports System.Text
Namespace dllInvocationSpace
Public Class dllInvoker
' tried attributes but could not make it build:
' <DllImport("Thing1.dll", False, CallingConvention.Cdecl, CharSet.Ansi, "Baton", True, True, False, True)>
Declare Ansi Function Thing Lib "Thing1.dll" (ByVal Command As String, ByRef Buffer As String, ByRef BufferLength As Integer)
Shared Function dllCall(ByVal Command As String, ByRef Results As String) As Integer
Dim Buffer As StringBuilder = New StringBuilder(65536)
Dim retCode As Integer
Dim bufsz As Integer
bufsz = 65536
retCode = Thing(Command, Buffer, bufsz)
Results = Buffer
Return retCode
End Function
End Class
End Namespace
The current code doesn't build, because although I think I should be able to create a "buffer" that the C Dll can write data back into using a string builder, I haven't got it quite right. (Value of type System.Text.STringBuilder cannot be converted to 'String').
I have looked all over the newsgroups and forums and can not find an example where the C dll needs to pass between 1 and 64kbytes of data back (char *buffer, int bufferlen) to visual basic.net.