Search code examples
c#vb.netdllimportinteropservices

Converted From VB.NET to C# - Not Returning Values Correctly


The original VB.net, which is working perfectly:

Declare Function HolderName Lib "myCard.dll" (ByVal buf As String) As Integer
Declare Function Photo Lib "myCard.dll" (ByRef photo As Byte) As Integer

...

buff = Space(200) : res = HolderName(buff)
ShowMsg("HolderName():" & IIf(res = 0, "OK:" & Trim(buff), "FAIL"))

photobuf = New Byte(4096) {}
res = Photo(photobuf(0))
ShowMsg("Photo():" & IIf(res = 0, "OK", "FAIL"))
If res = 0 Then
    Dim ms As New MemoryStream(photobuf)
    picImage.Image = Image.FromStream(ms)
End If

The converted code now in C# (using http://converter.telerik.com/)

using System.Runtime.InteropServices;

...

[DllImport("myCard.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int HolderName(String dBuff);

[DllImport("myCard.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int Photo(ref byte photo);

//...

buff = new String(' ', 200);
res = HolderName(buff);
// buff remains UNALTERED!
ShowMsg("HolderName():" + (res == 0 ? "OK:" + Strings.Trim(buff) : "FAIL"));

photobuf = new byte[4096];
res = Photo(ref photobuf[0]);
ShowMsg("Photo():" + (res == 0 ? "OK" : "FAIL"));

// photobuf successfully receives the data bytes from Photo function
if (res == 0)
{
    MemoryStream ms = new MemoryStream(photobuf);
    picImage.Image = Image.FromStream(ms);
}

The problem is buff remains unaltered even though the HolderName function actually returns some values (watched using USB Monitor). Why is this happening and how can I fix it?


Solution

  • Finally, I answered my own question. StringBuilder is the answer! Here's the codes...

            [DllImport("mykaddll.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
            public static extern int HolderName([Out] StringBuilder dBuff);
    
            //....
    
            StringBuilder sbBuff = new StringBuilder(200);
            res = HolderName(sbBuff);
            buf = sbBuff.ToString().Trim();
            ShowMsg("HolderName():" + (res == 0 ? "OK:" + buf : "FAIL"));