[Mono-dev] C++ embedding

Jonathan Pryor jonpryor at vt.edu
Tue Mar 21 07:01:54 EST 2006


On Mon, 2006-03-20 at 18:02 +0100, Denis ERCHOFF wrote:
> Hi all,
> 
> I am controlling some .Net class from C++ application.
> 
> I would like to know if from the C++ context i can add a "delegate like" 
> to a .Net property.
> I want to catch when a property's getter or a property's setter is 
> called from .Net context.
> I need to do some works when a public/private property is changed in the 
> Net environement.

Something similar to this can be done with the use of events.  See this
(uncompiled but should be reasonably close) example:

        class Interesting {
                private int property;
                
                public int Property {
                        get {
                                EventHandler e = PropertyAccessed;
                                if (e != null) e (this, new EventArgs
                                ());
                                return this.property;
                        }
                        set {
                                EventHandler e = PropertyChanged;
                                if (e != null) e (this, new EventArgs
                                ());
                                this.property = value;
                        }
                }
                
                // use an event to let code know when Property changed
                public event EventHandler PropertyAccessed;
                
                // use an event to let code know when Property changed
                public event EventHandler PropertyChanged;
        }
        
        class NativeCode {
                [DllImport ("native")]
                public static extern void NativeFunction ();
        }
        
        class Test {
                public static void Main ()
                {
                        Interesting i = new Interesting ();
                        i.PropertyChanged += 
                        	delegate {NativeCode.NativeFunction ();}
                        i.PropertyAccessed +=
                        	delegate {NativeCode.NativeFunction ();}
                        i.Property = 42;
                }
        }

You'd probably want to change the type of the events to something more
reasonable (so that you know what the current property value is), and
NativeCode.NativeFunction should probably take some parameters, but
something like that should allow your C/C++ code know when a C# property
is accessed or changes.

The downside is that this requires changes to the C# code.  If you don't
want to do any changes to the C# code, you're basically requiring a
debugger, so you should check out the debugger sources (and try to get
them working)...

 - Jon





More information about the Mono-devel-list mailing list