[Mono-dev] PInvoke and language interopelability

Alfredo José Muela Romero alfredoj.muela at gmail.com
Tue Jan 13 11:17:46 EST 2009

2009/1/13 Jonathan Pryor <jonpryor at vt.edu>

> 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
Hi Jon,

I'm aware about the delegate's marshalling, as I far as I understood and
test them they seemed pretty much as a function pointer... I'm glad I got it
right :)

The issue is about giving the pointer to the object and access to the method
through the object.

My thoughts were now on giving an extra functionallity to a proxy class
which would use that function pointer (delegate in C#) to perform the
callback. However, I guess that adding that indirection level may not be too
"elegant" :S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/mono-devel-list/attachments/20090113/b818cf2c/attachment.html 

More information about the Mono-devel-list mailing list