I'm using a C++ dll in C# and have problems with passing char* to it and back.
First of all the function looks the following:
[DllImport("xyz.dll")]
public static extern int ReadWrite_VCP(IntPtr handle, ref DATA_BUFFER readBuffer, ref DATA_BUFFER writeBuffer, int timeout);
The struct is defined as:
public struct DATA_BUFFER
{
public string buffer;
[MarshalAs(UnmanagedType.U4)]
public int length;
[MarshalAs(UnmanagedType.U4)]
public int transferCount;
}
The function call is:
ReadWrite_VCP(handle, ref rBuffer, ref wrBuffer, 5000);
In general this works fine, but the problem is, that the ReadWrite_VCP function writes a char array (including '\\0' characters). This results in the problem that if the data is '\\0' '1' '2' '3' , The string is empty as it is terminated by '\\0'.
I've already tried to use Stringbuilder or byte array, without any success.
On C++ Side the function looks like:
typedef struct
{
UCHAR *buffer;
UINT32 length;
UINT32 transferCount;
} DATA_BUFFER ;
And the Function:
unsigned int ReadWrite_VCP (HANDLE handle, DATA_BUFFER* ReadBuffer, DATA_BUFFER* writeBuffer, UINT32 timeout);
I hope anyone can help me!
Thank you!
Yes you were totally right!
my struct changed to:
public struct DATA_BUFFER
{
public IntPtr buffer;
[MarshalAs(UnmanagedType.U4)]
public int length;
[MarshalAs(UnmanagedType.U4)]
public int transferCount;
}
and before I call the function a allocate a Byte array and set the pointer to it
buf.length = 10;
byte[] input = new byte[buf.length];
buf.buffer = Marshal.UnsafeAddrOfPinnedArrayElement(input, 0);
Thank you!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.