【发布时间】:2018-10-05 02:56:57
【问题描述】:
我在调用 CPP dll 时遇到了一个非常奇怪的问题。
我可以调用传递一个结构数组(具有多个位置)的方法,并对其进行循环和设置数据。但是当代码回到 C# 时,数组只有一个位置。
例如,我创建了一个具有 3 个位置 (0, 1, 2) 的结构数组,在 C++ Dll 中我接收整个数组并且不对其执行任何操作,当执行返回到 C# Caller 时,数组在数组中只有一个位置,第一项。
代码:
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)]
- [进出]
- 阅读其他问题,但没有一个问题存在。
有人知道我错过了什么吗?
提前致谢!
【问题讨论】:
标签: c# c++ dll interop dllimport