如何在 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?
为澄清起见,以下示例代码导致编译器错误 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 事件,您可以按如下方式更新您的托管类(基于 这个建议):
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>()
形式.
Note the alternate bind<R>()
form that's used.
这篇关于如何在 C++/CLI 中使用 boost::bind 绑定托管类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!