将结构数组BYRE从C#传递到C ,然后将其恢复

Pass a Struct array ByRef from C# to C++ and get it back

本文关键字:然后 恢复 数组 结构 BYRE      更新时间:2023-10-16

呼叫CPP dll时我一个非常奇怪的问题。

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

例如,我在C dll中创建一个具有3个位置(0、1、2(的结构的数组阵列上只有一个位置,第一个项目。

代码:

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(UNMANAGGEDTYPE.LPARRAY(]
  • [IN,OUT]
  • 阅读其他问题,但没有一个问题。

有人对我错过的东西有任何了解吗?

预先感谢!

我解决了问题。

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

最后,我更改为C 中的void * paramStruct,最后都起作用了!