简体   繁体   English

将字节数组从C导入C#

[英]Getting byte array from C into C#

I have the following C function that I need to call from C#: 我有以下C函数,需要从C#调用:

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

I've declared the following on the C# side: 我在C#端声明了以下内容:

[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. 问题是chars / bytes数组将为0,并且将终止字符串,因此我不会找回整个消息。 Any ideas how I can refactor to get array of bytes back? 有什么想法可以重构以获取字节数组吗?

With jdweng help, I've changed the declaration to: 在jdweng帮助下,我将声明更改为:

[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. 而且,我正在分配和释放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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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