Click to See Complete Forum and Search --> : interop issue: wrapping a library that implements an observer-pattern?


Ralf A.
August 4th, 2006, 10:49 AM
Hi,

I've got a problem with my wrapper class and my wrapped native object:
How can the wrapper be notified if the native object inside is modified?

Background: I want to wrap a library where an observer pattern is implemented. There the native observer observes a native subject where it was registered. If the subject notifies the registered observers about a change my observer-wrapper was not notified.
What should I do to make this work? I thought about something like function pointers and delegates but I think I'm on the wrong track.

Or is it possible to pass a managed object as a parameter to a native object's function?
Example:

class AbstractSubject
{
public:
virtual ~AbstractSubject() {};
virtual void Attach(IObserver*);
virtual void Detach(IObserver*);
virtual void Notify();
protected:
AbstractSubject() {};
private:
std::vector observers;
};

class IObserver
{
public:
virtual ~IObserver() {};
virtual void Update(AbstractSubject* theChangedSubject) = 0;
protected:
IObserver() {};
};



As you can see the IObserver is a interface class. This interface class is wrapped by a managed c++ interface-class. The native observer object registeres itself on the Attach(IObserver*)-method and is added to the observers-vector.
If the Nofify()-method of the subject is called the subject iterates over the observers-vector and calls Update(this) (observerobject->Update(this)) on the observer object to notify the observer that something changed.

But how can I add now my managed class or my managed object to the subject to be notified? Please correct me when I'm wrong but I think I cannot pass the managed-observer-handle to the native method to notify the managed observer.

BTW: I don't have to source code for the native classes. I only have got a DLL-file, a LIB-file and some header-files to access the classes in the native lib.

Any help would be appreciated.

Thanks a lot for you help!

Best regards,
Ralf

darwen
August 9th, 2006, 06:56 AM
You need to wrap your managed class in a native class to be passed through the native call.

Have a look at my article here ('http://www.codeguru.com/Csharp/.NET/net_general/patterns/article.php/c8381') which shows something similar.

The key to doing what you're trying to do is in the "CNativeDerived" class, which is a native class providing an interface to the managed class.

The gcroot<> member of this class contains the managed reference, but in a native context.

Darwen.