I am trying to wrap an unmanaged c++ interface composed of several abstract structs (with all pure virtual methods) and a small factory namespace which returns handles (shared_ptrs) to these structs.
It seems that, because of this, I might be able to get away with merely marshalling pointers through as System.IntPtr types (although them being of type boost::shared_ptr, would that be ok or do i need additional handling?) and passing them around to simple managed wrappers and then back into the native code without the need to every worry what they point to. Is this on the right track?
I would appreciate any help or references to data marshalling with pinvoke for STL types or shared_ptr types (all i can find is very little on MSDN and other sites on strings and structs of primitives.)
Thank you,
I recommend defining a C API to be consumed by the .NET layer. Use
void *orconst void *for the “handle” types to your structures, and define anextern "C"function for each of the methods (including factory methods and the destructor). You can’t marshal ashared_ptr<T>argument directly, so you need to use thevoid *handles.In the .NET layer, first define a type derived from
SafeHandlewhose sole purpose is to dispose the handle correctly (i.e., call the C API representing the object destructor). Next, define a wrapper type that represents the actual object, and has methods for each of the C API functions that represent member functions of the object. Finally, define a factory type that wraps the C API factory methods.It’s a lot of work, but this is the correct way to do it.