C# Marshalling unsigned char* array from C++ DLL (in and out)

房东的猫 提交于 2019-12-08 14:07:13

问题


I am having trouble marshalling data between a C# application and an existing C++ DLL. The caveats that are making this difficult are that it is an unsigned char pointer to an array, and I need access to the data (from all fields) after the call in C#. I would like to avoid using unsafe code, if at all possible.

Here is the C++ signature:

BYTE GetData(unsigned char *Data_Type, unsigned char *Data_Content, unsigned int *Data_Length);

I've tried a bunch of things in C#, but here's what I have now:

[DllImport("somecpp.dll")]
public static extern byte GetData([In][Out] ref byte Data_Type, [In][Out] ref byte[] Data_Content, [In][Out] ref int Data_Length);

Then calling it, I am attempting this:

byte retrievedData = GetData(ref data_type, ref data_content, ref data_length);

This is definitely not working, and I'm not sure what to try next. Any ideas? Thanks!


回答1:


Your ref byte[] parameter matches unsigned char**. That's one level of indirection too many.

The p/invoke should be

[DllImport("somecpp.dll")]
public static extern byte GetData(
    ref byte Data_Type,
    [In,Out] byte[] Data_Content,
    ref uint Data_Length
);

It is plausible that the function uses cdecl. We can't tell that from here.

I also suspect that the Data_Type argument should be out rather than ref.



来源:https://stackoverflow.com/questions/28097528/c-sharp-marshalling-unsigned-char-array-from-c-dll-in-and-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!