[Mono-list] C++ interop with Mono

Robert Jordan robertj at gmx.net
Tue Nov 13 19:06:01 UTC 2012

On 13.11.2012 18:50, obiwanjacobi wrote:
> Ok, I get the "call unmanaged C++ code from managed C# code" examples.
> But I need something that works the other way around. The lifetime sequence
> starts of with a call to an (unmanaged C++) exported dll method
> (GetObjectFactory). I will implement the function in C++ but in that method
> I want to new-up a managed equivalent factory object and return the
> unmanaged representation of that (interface) -as a COM callable wrapper-
> from the exported function.
> I thought of making that managed factory object a managed COM object (with
> clsid) and simply call CoCreateInstance on it, but I would rather not do
> that because I don't know how that is supported on Mac and Linux...?
> Is there a way to create a managed object in unmanaged code in mono? (so
> without using MS CLI ;-)

You can pass the result of Marshal.GetComInterfaceForObject (an
IUnknown pointer) to C++ using an export and a function pointer:


extern "C" {
   void RegisterFactory(FactoryFunction ptr);


static extern void RegisterFactory(FactoryDelegate ptr);

public delegate IntPtr FactoryDelegate(....);

RegisterFactory(delegate (....) {
   object o = ....;
   return Marshal.GetComInterfaceForObject(o, SomeCOMInterfaceType);

Since you don't have a registry, you must come up with a
"protocol" that describes which class to instantiate.
The "protocol" is what I've left out in the sample above
(the dots).


More information about the Mono-list mailing list