Search code examples
c#c++pinvoke

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


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>>?


Solution

  • 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