views:

47

answers:

1

I am exposing some ISO C++ data types to .Net (mono on Linux to be precise).

For the purpose of brevity, I shall refer to C# in my question, although my question relates to all of the .Net languages (with C# and VB.Net being my target languages).

So far, I have worked out how to expose the ISO C++ data types in C# class(es) for use in mono - thanks to some of the clever guys here on SO.

The only problem so far is how to deal with the C++ callbacks. In .Net languages (C# and Vb.Net), I believe 'delegates' are the callback equivalent.

Sticking with C# for now, can anyone recommend a way that I can register the C# delegate functions with my ISO C++ code.

The ISO C++ code is a notification library, and I want to be able to "push" the notifications to the mono framework (i.e. C# delegates in this case).

My underlying assumption is that the mechanism/steps to implement this would be the same for the .Net languages - I'll just have to code the actual delegates in the .Net language of choice - is that assumption correct?

Last but not the least, is the question of thread saftey. The underlying ISO C++ code that I am exposing to .Net (mono to be more specific), is both re-ntrant and thread safe - do I have to do anything "extra" to call .Net delegate from my ISO C++ code?

+2  A: 

Just make sure the function pointer you define and use in C++ has C linkage. You can then export a C function that takes the function pointer as an argument and you'll P/invoke that with the delegate as argument from C#.

From the C++ side you will just call through the function pointer normally.

Note that you will have to keep the delegate object alive for as long as the C callback can be called, likely storing the delegate in a static var or similar, if the C callback is to be stored to be executed at a later time than registration.

As for the rest, you can't safely call managed code from signal handlers: apart from that as long as your managed code is reentrant and thread safe, so will be the delgate/callback combination.

lupus
@lupus: thanks for your answer (its me - the OP). Unfortunately, I appear to have lost my session based login info,so I cant mark this answer as accepted - even though it is helpful.
skyeagle
@lupus: could you point me to some documentation that provides an example of doing this?
skyeagle
I have two links that together, you should be able to figure this out, I would think. The first is from MSDN, and just gives an overview of using delegates for callbacks: < http://msdn.microsoft.com/en-us/library/843s5s5x >. This second one is an example using GCC/Mono: < http://www.huronbox.com/~james/techdemos/cs-callback.html >.
supercheetah
@supercheetah: thanks
skyeagle