Boost logo

Boost Users :

From: Bjorn.Karlsson_at_[hidden]
Date: 2005-01-19 04:00:49


Hello Vasco,

> From: Vasco Lohrenscheit [mailto:valoh_at_[hidden]]
>
> is there a easy way/workaround to use methods of managed classes with
> boost::bind?

It's not exactly easy, but I think it can be done.

First of all, you won't be able to take the address of
TestManagedClass::test because it's a managed class. Second, the calling
conventions of invoking the signal (default: __stdcall) and the function
test (__clrcall) are different. Here's a workaround that should work:

* Create a nested __nogc class in the __gc class (technically, it doesn't
need to be nested, just __nogc).
* In the nested class, store a pointer (using gcroot<>, as it's a managed
class) to the outer class.
* In the constructor of the outer class, create an instance of the nested
class.
* Define a callback member in both classes. In the inner class, simply
forward to the corresponding function in the outer class.
* Create the bind expression using the address of the nested class'
function.
* Invoke the signal and keep your fingers crossed.

Here's an example that demonstrates the technique:

  #include "boost/bind.hpp"
  #include "boost/signals.hpp"
  #include "vcclr.h" // For gcroot<>

  boost::signal<void (int)> sig;

  __gc class managed_class {
  public:
    managed_class() : inner_(new unmanaged_class(this)) {
      // Connect to the signal
 
sig.connect(boost::bind(&managed_class::unmanaged_class::callback,inner_,_1)
);
    }

    void callback(int i) {
      // This is the managed "callback"
    }

  private:
    // Here's the nested class
    __nogc class unmanaged_class {
    public:
      unmanaged_class(managed_class* outer) : outer_(outer) {}

      void callback(int i) {
        outer_->callback(i);
      }
    private:
      gcroot<managed_class*> outer_;
    };

    unmanaged_class* inner_;
  };

  void main() {
    managed_class* p=new managed_class();
    sig(42); // Invokes the signal,
             // which invokes the binder,
             // which invokes unmanaged_class::callback(),
             // which invokes managed_class::callback().
  }

Bjorn Karlsson


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net