[Mono-dev] PInvoke and language interopelability

Jonathan Pryor jonpryor at vt.edu
Tue Jan 13 11:03:54 EST 2009

On Tue, 2009-01-13 at 16:13 +0100, Alfredo José Muela Romero wrote:
> My current problem, which I'm running out of ideas :/ is about how to
> get a call from the dinamic to the wrapped code.
> Let's say I have a dynamic library (in C++ for instance) which
> implements a Model-View-Controller pattern. In that library exists a
> method which receives a pointer to an object as a parameter in order
> to notify later changes.
> Does anyone know a way to get that call to the C# code

Delegates are your friend.  Delegates marshal to a function pointer that
can be called from C/C++ code, e.g. given:

	delegate int Foo (string s);
	[DllImport] static extern void PerformCallback(Foo f);

	Func<string, int> f = s => s.Length;
	PerformCallback (f);
	f = null;

The C++ code would be:

	void PerformCallback(int (*cb)(const char* s))
		cb ("hello!");

This works pretty well for functions.  If you need to pass actual C++
objects around, things get more complicated.  You might be able to
create a C# class/structure to mirror the C++ type, but such things can
get ugly, quick.

Note: delegates passed to native code are only valid for as long as the
managed delegate exists.  In the above code, the native callback will
only be valid for the life of the PerformCallback() call.  If you need
it to last longer, you'll need to store the delegate as a member and
otherwise ensure it isn't collected.

 - Jon

More information about the Mono-devel-list mailing list