如何在C ++ / CLI中使用boost :: bind绑定托管类的成员 [英] How to use boost::bind in C++/CLI to bind a member of a managed class
问题描述
我在本地C ++类中使用boost :: signal,现在我在C ++ / CLI中编写一个.NET包装器,以便将本机C ++回调作为.NET事件公开。当我尝试使用boost :: bind获取我的托管类的成员函数的地址,我得到编译器错误3374,说我不能取成员函数的地址,除非我创建一个委托实例。有没有人知道如何使用boost :: bind绑定托管类的成员函数?
I am using boost::signal in a native C++ class, and I now I am writing a .NET wrapper in C++/CLI, so that I can expose the native C++ callbacks as .NET events. When I try to use boost::bind to take the address of a member function of my managed class, I get compiler error 3374, saying I cannot take the address of a member function unless I am creating a delegate instance. Does anyone know how to bind a member function of a managed class using boost::bind?
为了说明,下面的示例代码导致Compiler Error 3374:
For clarification, the following sample code causes Compiler Error 3374:
#include <boost/bind.hpp>
public ref class Managed
{
public:
Managed()
{
boost::bind(&Managed::OnSomeEvent, this);
}
void OnSomeEvent(void)
{
}
};
推荐答案
到世界(Managed :: OnSomeEvent)。如果你不希望人们能够通过调用OnSomeEvent()来引发OnChange事件,那么你可以如下更新你的Managed类(基于此建议):
While your answer works, it exposes some of your implementation to the world (Managed::OnSomeEvent). If you don't want people to be able to raise the OnChange event willy-nilly by invoking OnSomeEvent(), you can update your Managed class as follows (based on this advice):
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<ChangeCallback>( ip.ToPointer() );
*callback = native->RegisterCallback(boost::bind<void>( cbFunc ) );
}
Managed::~Managed()
{
native->UnregisterCallback(*callback);
delete callback;
if ( gch.IsAllocated )
{
gch.Free();
}
}
void Managed::OnSomeEvent(void)
{
OnChange();
}
请注意备用 bind< R& / code>使用的表单。
Note the alternate bind<R>()
form that's used.
这篇关于如何在C ++ / CLI中使用boost :: bind绑定托管类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!