[Mono-list] Can I call c# code from c code?

Miguel de Icaza miguel at novell.com
Wed Feb 14 14:43:26 EST 2007


> I have a large C# project that runs under Windows and makes use of C-DLLs that have callbacks into the C# code.
> I am trying to figure out if it's possible to port all of this to
> mono.  I understand how to call C code from C# and how to embed the
> mono runtime in C code, but I don't see a way to do what I need
> without embedding mono.

There is a simple way.    Lets say that your C code needs to call this
function in C#:

class Dingus { void DoDingus (int operation); }

So you define this in C#:

	delegate void MyCallback (int operation);

Then you create a delegate of this type:

	Dingus d = new Dingus ();
	MyCallback do_dingus_callback = new MyCallback (d.DoDingus);

So now you have a delegate that you can use to call DoDingus from C#
that would be:

	do_dingus_callback (10);

That would call `d.DoDingus' with the parameter 10. 

You are not limited to calling instance methods, it could be a static

Now, you need to pass this delegate to the unmanaged world, like this:

	[DllImport ("...")]
	extern static void Native_Code_Do_Something (MyCallback cback);


	Native_Code_Do_Something (do_dingus_callback)

In C, you then write:

typedef void (*callback)(int op)

void Native_Code_Do_Something (callback cb)
	cb (10);


More information about the Mono-list mailing list