简体   繁体   English

C#导入C Dll。 struct中的数组指针。 如何?

[英]C# import C Dll. Array pointer in struct. How to?

I need your help. 我需要你的帮助。

I am trying to import a C Dll into a C# project. 我正在尝试将C Dll导入C#项目。 While doing that, I need pass a struct between the Dll and C# project in both directions. 这样做时,我需要在两个方向的Dll和C#项目之间传递一个结构。

Here is C definition: 这是C的定义:

struct mwBITMAP 
{
 int bmWidth;
 int bmHeight;
 BYTE* bmData;
}; 

Here is C# definition: 这是C#定义:

   [StructLayout(LayoutKind.Sequential)] 
    public struct MwRemoteBmp
    {
        public int Width;
        public int Height;
        public byte[] Data;
    }

I tried to pass the a struct (the Data is well initialized) from C# to a dll's test function by reference. 我试图通过引用将C#的结构(数据已正确初始化)传递给dll的测试函数。 The width and height are both right. 宽度和高度都正确。 But the Data is all wrong. 但是数据全错了。

Where did I make mistakes? 我在哪里犯错?

Yes, the array gets marshaled as a SAFEARRAY. 是的,该阵列被封为SAFEARRAY。 Not crashing the pinvoke marshaller is pretty unusual. 不撞掉pinvoke编组员是很不寻常的。 Declare the Data member as IntPtr, then use Marshal.Copy() to copy the data. 将Data成员声明为IntPtr,然后使用Marshal.Copy()复制数据。

Beware that this would be hard to use in C as well. 注意,这在C语言中也很难使用。 There's a memory management problem, it isn't clear who owns the array. 存在内存管理问题,尚不清楚谁拥有该阵列。 Most typically, the C function would use malloc() to allocate the array. 最典型的是,C函数将使用malloc()分配数组。 That's a big problem, you cannot release that array in C#, no way to call free(). 这是一个大问题,您无法在C#中释放该数组,无法调用free()。 You'll have an unpluggable memory leak. 您将发生无法插拔的内存泄漏。 If you can't rewrite the C code then you'll need to write a wrapper in the C++/CLI language so that you can call free(). 如果您不能重写C代码,则需要用C ++ / CLI语言编写包装器,以便可以调用free()。 Even that is tricky if the C dll doesn't use the same CRT as the C++/CLI code. 如果C dll不使用与C ++ / CLI代码相同的CRT,则即使这很棘手。 You have to compile the C code with the /MD option. 您必须使用/ MD选项编译C代码。

Use the IntPtr type instead of byte[] type. 使用IntPtr类型而不是byte []类型。 In your example: 在您的示例中:

[StructLayout(LayoutKind.Sequential)] 
public struct MwRemoteBmp
{
    public int Width;
    public int Height;
    public IntPtr Data;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM