[Mono-dev] C++ to C# to C++ interop, how can I do this in a mono-compliant way?

Miguel de Icaza miguel at ximian.com
Thu Sep 1 10:17:21 EDT 2005


Hello,
 
> Is there any way to have this work under Mono?   Please realize that
> the basic need is to have 1 instance of a C++ exe call into a .NET
> dll, and have that DLL be able to then execute functions in the C++
> exe that called it.     So this requires a mono-equivlant of PInvoke,
> plus a way to have the C++ app call the C# app. 
>  
> Help on this would be appreciated, otherwise it'll be Windows only!

If you do not mind writing some bridge code, just use P/Invoke on the C#
side to call your C++ code.

Notice that all the entry points that you will access have to be:

	extern "C" { .... }

So that P/Invoke can locate them.

For calling from C++ to managed land, you can use function pointers:
register a delegate as a function pointer with your C++ code and have
that be your gateway to communicate back:

file.c:
	typedef void (*mono_print_hello_fn) ();
	mono_print_hello_fn printer;

	routine ()
	{
		(*printer) ();
	}

	set_hello_func (mono_print_hello_fn f)
	{
		printer = f;
	}

>From C# you call:

	delegate void MyPrinter ();
	[DllImport (...)]
	extern static int set_hello_func (MyPrinter f);

	Main ()
	{
		set_hello_func (new MyPrinter (func));
		
	}

	void MyPrinter ()
	{
		Console.WriteLine ("Hello");
	}



More information about the Mono-devel-list mailing list