C# 从 C++ DLL 编组 unsigned char* 数组(输入和输出)

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

我在 C# 应用程序和现有 C++ DLL 之间编组数据时遇到问题。使这变得困难的警告是它是一个指向数组的无符号字符指针,我需要在 C# 中调用后访问数据(来自所有字段)。如果可能的话,我想避免使用不安全的代码。

这是 C++ 签名:

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

我已经在 C# 中尝试了很多东西,但这是我现在所拥有的:

[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);

然后调用它,我正在尝试这样做:

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

这绝对行不通,我不确定接下来要尝试什么。有任何想法吗?谢谢!

您的 ref byte[] 参数匹配 unsigned char**。这是一个间接级别太多了。

p/invoke应该是

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

函数使用cdecl是合理的。我们不能从这里说出来。

我还怀疑 Data_Type 参数应该是 out 而不是 ref