c# - 将结构数组 ByRef 从 C# 传递到 C++ 并将其取回

标签 c# c++ dll interop dllimport

我在调用 CPP dll 时遇到一个非常奇怪的问题。

我可以调用传递一个结构数组(具有多个位置)的方法,编码并循环它并为其设置数据。但是当代码返回到 C# 时,数组只有一个位置。

例如,我创建了一个包含 3 个位置 (0, 1, 2) 的结构数组,在 C++ Dll 中我接收了整个数组但不对其进行任何操作,当执行返回到 C# 调用程序时,数组在数组中只有一个位置,即第一项。

代码:

C++ 方面:

extern "C" __declspec(dllexport) int ViewItems(int * nTotalItems, void ** paramStruct) 
{
    // TODO nothing here.
    return 1;
}

C# 端:

[DllImport(@"MyCustomLib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ViewItems(ref int resultItemsCount, ref MyStruct[] MyStruct);

调用:

var resultSize = 3;
var resultStruct = new MyStruct[3];

for (int i = 0; i < resultSize; i++)
{
    resultStruct[i].SomePropValue = i+2;
}

// Before this, the resultStruct.Lenght is 3    
var resultCall = ViewItems(ref resultSize, ref resultStruct);
// After this, the resultStruct.Lenght is 

结构:

[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    public int SomePropValue;
}

我尝试了以下但没有成功:

  • [MarshalAs(UnmanagedType.LPArray)]
  • [进,出]
  • 阅读其他问题,但没有一个有这个问题。

有人知道我错过了什么吗?

提前致谢!

最佳答案

我解决了这个问题。

我从 DllImport 中删除了 ref 并将 [MarshalAs(UnmanagedType.LPArray)][In, Out ] MyStruct 参数中的装饰器。

最后,我在C++中改成了void * paramStruct,终于全部成功了!

关于c# - 将结构数组 ByRef 从 C# 传递到 C++ 并将其取回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008590/

相关文章:

c# - 引入 Visual Studio 2015 的问题

c# - 读取已打印到控制台的值

c# - 登录时存储用户信息的选项

c++ - 包含 dshow.h 会导致定义错误

c# - C# 中的数组声明语法是否有原因?

c++ - C++ 中的自定义 I/O 操纵器用于填充

c++ - 具有数据成员语法的零成本属性

c++ - 在没有函数修饰的情况下导出 dll 中的类

.net - 将我的 DLL 部署到 GAC 以与 ClickOnce 应用程序一起使用

dll - 同时注册32位和64位DLL