我在本机C++类中使用boost :: signal,现在我在C++/CLI中编写.NET包装器,这样我就可以将本机C++回调公开为.NET事件.当我尝试使用boost :: bind来获取托管类的成员函数的地址时,我得到编译器错误3374,说我不能获取成员函数的地址,除非我创建一个委托实例.有谁知道如何使用boost :: bind绑定托管类的成员函数?
为了澄清,以下示例代码导致编译器错误3374:
#includepublic ref class Managed { public: Managed() { boost::bind(&Managed::OnSomeEvent, this); } void OnSomeEvent(void) { } };
BKewl.. 10
虽然您的答案有效,但它会将您的一些实现暴露给全世界(Managed :: OnSomeEvent).如果您不希望人们通过调用OnSomeEvent()而无所事事地引发OnChange事件,则可以按如下方式更新Managed类(基于此建议):
public delegate void ChangeHandler(void); typedef void (__stdcall *ChangeCallback)(void); public ref class Managed { public: Managed(Native* Nat); ~Managed(); event ChangeHandler^ OnChange; private: void OnSomeEvent(void); Native* native; Callback* callback; GCHandle gch; }; Managed::Managed(Native* Nat) : native(Nat) { callback = new Callback; ChangeHandler^ handler = gcnew ChangeHandler( this, &Managed::OnSomeEvent ); gch = GCHandle::Alloc( handler ); System::IntPtr ip = Marshal::GetFunctionPointerForDelegate( handler ); ChangeCallback cbFunc = static_cast( ip.ToPointer() ); *callback = native->RegisterCallback(boost::bind ( cbFunc ) ); } Managed::~Managed() { native->UnregisterCallback(*callback); delete callback; if ( gch.IsAllocated ) { gch.Free(); } } void Managed::OnSomeEvent(void) { OnChange(); }
请注意使用的替代bind
形式.
虽然您的答案有效,但它会将您的一些实现暴露给全世界(Managed :: OnSomeEvent).如果您不希望人们通过调用OnSomeEvent()而无所事事地引发OnChange事件,则可以按如下方式更新Managed类(基于此建议):
public delegate void ChangeHandler(void); typedef void (__stdcall *ChangeCallback)(void); public ref class Managed { public: Managed(Native* Nat); ~Managed(); event ChangeHandler^ OnChange; private: void OnSomeEvent(void); Native* native; Callback* callback; GCHandle gch; }; Managed::Managed(Native* Nat) : native(Nat) { callback = new Callback; ChangeHandler^ handler = gcnew ChangeHandler( this, &Managed::OnSomeEvent ); gch = GCHandle::Alloc( handler ); System::IntPtr ip = Marshal::GetFunctionPointerForDelegate( handler ); ChangeCallback cbFunc = static_cast( ip.ToPointer() ); *callback = native->RegisterCallback(boost::bind ( cbFunc ) ); } Managed::~Managed() { native->UnregisterCallback(*callback); delete callback; if ( gch.IsAllocated ) { gch.Free(); } } void Managed::OnSomeEvent(void) { OnChange(); }
请注意使用的替代bind
形式.