从 C 获取字节数组到 C#

Getting byte array from C into C#

我需要从 C# 调用以下 C 函数:

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

我在 C# 端声明了以下内容:

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

我是这样调用函数的:

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

这在我收到 "string" 消息的初始测试中运行良好。但是,现在我想接收打包消息(chars/bytes 的数组)。问题是 chars/bytes 的数组将包含 0 并将终止字符串,因此我无法取回整个消息。有什么想法可以重构以取回字节数组吗?

在 jdweng 的帮助下,我将声明更改为:

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

而且,我正在 C# 端分配和释放内存以及编组数据。

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);
}