【问题标题】:Pass a Struct array ByRef from C# to C++ and get it back将 Struct 数组 ByRef 从 C# 传递到 C++ 并取回
【发布时间】: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


    【解决方案1】:

    我解决了这个问题。

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

    最后,我在 C++ 中更改为void * paramStruct,终于一切正常!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-30
      • 2016-04-06
      • 1970-01-01
      • 2013-05-03
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多