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. While doing that, I need pass a struct between the Dll and C# project in both directions.
Here is C definition:
struct mwBITMAP
{
int bmWidth;
int bmHeight;
BYTE* bmData;
};
Here is C# definition:
[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. The width and height are both right. But the开发者_Go百科 Data is all wrong.
Where did I make mistakes?
Yes, the array gets marshaled as a SAFEARRAY. Not crashing the pinvoke marshaller is pretty unusual. Declare the Data member as IntPtr, then use Marshal.Copy() to copy the data.
Beware that this would be hard to use in C as well. 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. That's a big problem, you cannot release that array in C#, no way to call 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(). Even that is tricky if the C dll doesn't use the same CRT as the C++/CLI code. You have to compile the C code with the /MD option.
Use the IntPtr type instead of byte[] type. In your example:
[StructLayout(LayoutKind.Sequential)]
public struct MwRemoteBmp
{
public int Width;
public int Height;
public IntPtr Data;
}
精彩评论