How do I import and call unmanaged C dll with ANSI C string “char *” pointer string from VB.NET?

后端 未结 2 1847
清酒与你
清酒与你 2020-12-21 16:34

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, i         


        
相关标签:
2条回答
  • 2020-12-21 17:14

    You cannot convert a StringBuilder instance to a string instance, instead, use the 'ToString' method to convert it back to the string type...here's the portion of the code in the dllCall function...

    retCode = Thing(Command, Buffer, bufsz)
    Results = Buffer.ToString();
    
    0 讨论(0)
  • 2020-12-21 17:18

    It depends on how you use the buffer argument in your C code. If you only pass a string from your VB.NET code to your C code then declaring it ByVal String is good enough. If however you let the C code return a string in the buffer then you have to declare it ByVal StringBuilder and initialize it properly before the call. For example:

    Public Class dllInvoker
        Declare Ansi Function Thing Lib "Thing1.dll" (ByVal Command As String, ByVal Buffer As StringBuilder, ByRef BufferLength As Integer) As Integer
    
        Shared Function dllCall(ByVal Command As String, ByRef Results As String) As Integer
            Dim Buffer As StringBuilder = New StringBuilder(65536)
            Dim Length As Integer = Buffer.Capacity
            Dim retCode As Integer = Thing(Command, Buffer, Length)
            Results = Buffer.ToString()
            Debug.Assert(Results.Length = Length)
            Return retCode
        End Function
    End Class
    

    Note the ambiguity in the returned Length value.

    0 讨论(0)
提交回复
热议问题