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

标签 c# c++ dllimport managed dllexport

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

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() 的调用。请参阅下面的示例,了解我认为可行的方法。

两个大问题:

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

关于c# - 如何将两个非托管 C++ 函数包装到两个托管 C# 函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2777937/

相关文章:

c++ - FMA 性能与朴素计算的比较

C++ 未修改的 bool 数组更改 (OS X)

c++ - wxdev-C++ GDIplus问题

c++ - 在 Qt 应用程序中使用自定义 dll

C# 新手 : How do I fix this code to do a DNS lookup?

c# - MVVM 使用 INotifyPropertyChanged Model 不通知 ViewModel

c# - 用用户名和密码模拟?

c# - 通过 DllImport 在 C# 中调用 C 方法 - 尝试读取或写入 protected 内存

c# - 我需要一个网络应用程序中的通知系统

c# - WCF Restful POST 从服务器到客户端返回错误消息