如何将两个非托管C ++函数包装到两个托管C#函数中?

时间:2010-05-06 01:46:26

标签: c# c++ dllimport managed dllexport

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

unsigned char * Compress(unsigned char *,int)

unsigned char * Decompress(unsigned char *,int)

所有的uchars都是uchars阵列。

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

1 个答案:

答案 0 :(得分:1)

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

两个大问题:

  1. 调用者如何知道返回unsigned char * buffer中存储的数据大小?
  2. 如何为返回unsigned char * buffer分配内存?您是否需要释放它?如果需要,您将如何从C#中释放它?
  3. 样品:

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