如何使用P/Invoke在C#中返回列表? [英] How to return a list in C# using P/Invoke?
问题描述
我正在一个小项目中使用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参数). /p>
您可能会认为C#列表和std :: list可以双向编组,但事实并非如此.
相关问题:编组.NET泛型类型
I am working on a small project where I use P/Invoke and want to return the following in C#:
public: class std::list<int,class std::allocator<int> > const * __thiscall TransactionsModule_t::GetTransactionList(void)const
And now this is where I'm confused:
[DllImport("TransactionManager.dll", EntryPoint = "...", CallingConvention = CallingConvention.ThisCall)]
public static extern ??? GetTransactionList(
IntPtr interfacePtr);
I am sort of clueless as to where to even start looking, as I can't directly see what the return type is, well obviously it's a sort of list. That much I do understand, but is it a nested list? Perhaps a Dictionary Dictionary<int,List<int>>
?
You cannot do this. Template types, AFAIK, don't work with P/Invoke possibly because the runtime cannot figure out the length of the list/how to allocate & deallocate the required amount of memory, etc.
Your best bet will be to write a C++/CLI wrapper or change the return type in C++ to an int array or to pass in a parameter to the method that can be filled in the C++ side (an out parameter).
You might think that the C# list and the std::list can be marshalled both ways, but that is not the case.
Related question: Marshalling .NET generic types
这篇关于如何使用P/Invoke在C#中返回列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!