[Mono-dev] C++ to C# to C++ interop, how can I do this in a mono-compliant way?
William S Fulton
wsf at fultondesigns.co.uk
Sun Sep 4 04:00:26 EDT 2005
Miguel de Icaza wrote:
> 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");
> }
If you have many C++ functions to call from C#, consider using SWIG
http://www.swig.org to automate the generation of the PInvoke bridge
code. SWIG requires your C++ header files as input and generates C#
proxy classes for your C++ classes. The tool doesn't yet wrap callbacks
from C++ to C# using function pointers/delegates so you'll have to write
this by hand as shown above.
William
More information about the Mono-devel-list
mailing list