我有两个非托管 C++ 函数,Compress
和Decompress
. 参数和返回如下:
无符号字符* Compress
(无符号字符*,整数)
无符号字符* Decompress
(无符号字符*,整数)
其中所有 uchar 都是 uchar 数组。
有人可以帮我设计一种使用 Byte[] 数组而不是 unsigned char* 将这些转换为托管 C# 代码的方法吗?非常感谢你!
您应该能够将 unsigned char* 参数作为 byte[] 传递,标准 P/Invoke marshaller 应该处理它。您必须自己编组输出 unsigned char*,但这应该只是对 Marshall.Copy() 的调用。请参阅下面的示例,了解我认为可行的方法。
两个大问题:
样本:
[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;
}