0

我有两个非托管 C++ 函数,CompressDecompress. 参数和返回如下:

无符号字符* Compress(无符号字符*,整数)

无符号字符* Decompress(无符号字符*,整数)

其中所有 uchar 都是 uchar 数组。

有人可以帮我设计一种使用 Byte[] 数组而不是 unsigned char* 将这些转换为托管 C# 代码的方法吗?非常感谢你!

4

1 回答 1

1

您应该能够将 unsigned char* 参数作为 byte[] 传递,标准 P/Invoke marshaller 应该处理它。您必须自己编组输出 unsigned char*,但这应该只是对 Marshall.Copy() 的调用。请参阅下面的示例,了解我认为可行的方法。

两个大问题:

  1. 调用者如何知道返回的 unsigned char* 缓冲区中存储的数据大小?
  2. 如何为返回的 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;
    }
于 2010-05-06T02:05:08.237 回答