RE: [Boost-users] boost::bind and methods of managed classes

Hello Vasco,
From: Vasco Lohrenscheit [mailto:valoh@krautgames.de]
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
participants (1)
-
Bjorn.Karlsson@readsoft.com