如何使用P/Invoke在C#中返回列表

How to return a list in C# using P/Invoke?

本文关键字:返回 列表 Invoke 何使用      更新时间:2023-10-16

我正在处理一个小项目,在该项目中我使用p/Invoke,并希望在C#中返回以下内容:

public: class std::list<int,class std::allocator<int> > const * __thiscall TransactionsModule_t::GetTransactionList(void)const

现在我感到困惑的地方是:

[DllImport("TransactionManager.dll", EntryPoint = "...", CallingConvention = CallingConvention.ThisCall)]
public static extern ??? GetTransactionList(
    IntPtr interfacePtr);

我甚至不知道从哪里开始寻找,因为我无法直接看到返回类型是什么,很明显,这是一种列表。我理解这么多,但这是一个嵌套列表吗?也许是字典Dictionary<int,List<int>>

您不能这样做。模板类型AFAIK不适用于P/Invoke,可能是因为运行时无法计算列表的长度/如何分配&释放所需的内存量等。

最好的办法是编写一个C++/CLI包装器,或者将C++中的返回类型更改为int数组,或者将参数传递给可以在C++端填充的方法(out参数(。

您可能认为C#列表和std::列表可以双向排列,但事实并非如此。

相关问题:封送.NET泛型类型