【问题标题】:Execute C++ function from C# application从 C# 应用程序执行 C++ 函数
【发布时间】:2013-09-06 01:24:39
【问题描述】:

我有一个用 C++ 编写的 DLL,它是 C# 围绕 LZO 库的包装器。但出于测试目的,我想知道是否可以转换类型,所以我创建了一个测试函数,它接收文件的内容和大小并写入它的副本。

extern "C" 
{
     __declspec(dllexport) void WriteFile(lzo_uint8 * source, int size)
    {
        FILE * fileToWrite;
       fileToWrite = fopen("test.eix", "wb+");
       if (fileToWrite)
       {
          fwrite(source, 1, size, fileToWrite);
       }
       fclose(fileToWrite);
       free(source);
    }
  }

这是代码的图像,为了更好的可读性:http://i.epvpimg.com/u4mgh.png

然后我像这样导入它:

[DllImport(@"GLZO.dll")]
public static extern void WriteFile(byte[] source, int size);

然后这样称呼它:

        byte[] g = ReadFile("raw/roota.eix");
        WriteFile(g, g.Length);

问题不在 ReadFile 函数,我检查了一下。我从另一个文件创建了一个副本,并使用校验和进行了检查。

所以,我的问题是:我应该如何将 byte[] 转换为 lzo_uint8* (unsigned char*)?

【问题讨论】:

    标签: c# c++ type-conversion unmanaged-memory


    【解决方案1】:

    知道了!我只需要在 C# 中将其编组为 IntPtr, unsigned char * = IntPtr。

    此外,为避免出现“不等价”类型的异常,您需要按以下方式导入 dll:

            [DllImport(@"GLZO.dll", CallingConvention = CallingConvention.Cdecl)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-03
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 2013-06-01
      相关资源
      最近更新 更多