简体   繁体   中英

Getting byte array from C into C#

I have the following C function that I need to call from C#:

__declspec(dllexport) int receive_message(char* ret_buf, int buffer_size);

I've declared the following on the C# side:

[DllImport("MyCLibrary", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, EntryPoint = "receive_message")]
public static extern int ReceiveMessage([MarshalAs(UnmanagedType.LPStr)]StringBuilder retBuf, int bufferSize);

I'm calling the function like so:

StringBuilder sb = new StringBuilder();
int len = ReceiveMessage(sb, 512);

This works fine with my initial tests where I was receiving "string" messages. But, now I want to receive packed messages (array of chars/bytes). The problem is that the array of chars/bytes will have 0s and will terminate the string so I don't get back the whole message. Any ideas how I can refactor to get array of bytes back?

With jdweng help, I've changed the declaration to:

[DllImport("MyCLibrary", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, EntryPoint = "receive_message")]
public static extern int ReceiveMessage(IntPtr retBuf, int bufferSize);

And, I'm allocating and freeing the memory on the C# side along with marshalling the data.

IntPtr pnt = Marshall.AllocHGlobal(512);
try
{
   int len = ReceiveMessage(pnt, 512);
   ...
   byte[] bytes = new byte[len];
   Marshal.Copy(pnt, bytes, 0, len);
   ...
}
finally
{
   Marshal.FreeHGlobal(pnt);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM