I have a library whose functionality I want to eventually expose to .NET. The method I want to expose has the following signature:
void DoSomething(std::list<SomeStruct>& someList);
The variable someList gets populated by DoSomething.
I know how to export from the library already. My main question is what would a “.NET friendly” interface look like for this function? I’d assume that std::list is a bad idea if I want to use C# with P/Invokes.
What other options are there? As the caller, I won’t know the size of the buffer that I should pass in ahead of time. Also, as the caller, I’d rather not make multiple calls to the function with small fixed-sized buffers nor would I want to pass in a super large buffer.
What’s the best practice for this case?
You can define a struct for use in the pinvoke call. Decorate it on native and mnaged sides, so that the packing is the same on each side. As for the variable sized out parameter, you could use ::GlobalAlloc to allocate an array that can then be deallocated in C#. Pass out an item count as well. In C#, the Marshal type has various methods to use to work with a GlobalAlloc’d array.