How to use boost::bind in C++/CLI to bind a member of a managed class

后端 未结 2 626
無奈伤痛
無奈伤痛 2020-12-30 08:41

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

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 09:01

    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( 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();
    }
    

    Note the alternate bind() form that's used.

提交回复
热议问题