我有两个非托管 C++ 函数,Compress
和 Decompress
。参数和返回如下:
unsigned char* 压缩
(unsigned char*,int)
unsigned char* 解压缩
(unsigned char*,int)
其中所有 uchar 都是 uchar 的数组。
有人可以帮我找到一种方法,使用 Byte[] 数组而不是 unsigned char* 将它们转换为托管 C# 代码吗?非常感谢!
最佳答案
您应该能够将 unsigned char* 参数作为 byte[] 传递,标准的 P/Invoke 编码器应该处理它。您必须自己编码输出 unsigned char*,但这应该只是对 Marshall.Copy() 的调用。请参阅下面的示例,了解我认为可行的方法。
两个大问题:
- 调用者如何知道返回的 unsigned char* 缓冲区中存储的数据大小?
- 返回的 unsigned char* 缓冲区的内存是如何分配的?您是否必须释放它?如果需要,您将如何从 C# 中释放它?
示例:
[DllImport("Name.dll")]
private static extern IntPtr Compress([MarshalAs(UnmanagedType.LPArray)]byte[] buffer, int size);
[DllImport("Name.dll")]
private static extern IntPtr Decompress([MarshalAs(UnmanagedType.LPArray)]byte[] buffer, int size);
public static byte[] Compress(byte[] buffer) {
IntPtr output = Compress(buffer, buffer.Length);
/* Does output need to be freed? */
byte[] outputBuffer = new byte[/*some size?*/];
Marshal.Copy(output, outputBuffer, 0, outputBuffer.Length);
return outputBuffer;
}
public static byte[] Decompress(byte[] buffer) {
IntPtr output = Decompress(buffer, buffer.Length);
/* Does output need to be freed? */
byte[] outputBuffer = new byte[/*some size?*/];
Marshal.Copy(output, outputBuffer, 0, outputBuffer.Length);
return outputBuffer;
}
关于c# - 如何将两个非托管 C++ 函数包装到两个托管 C# 函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2777937/