【问题标题】:Combining function, bind, c++ and managed code结合函数、绑定、C++ 和托管代码
【发布时间】:2012-05-25 18:19:50
【问题描述】:

我有一个 c++ 函数,它期望将函数对象 (AuthenticateNotifyFunc) 传递给它:

class lc_Authenticate
{
public:
   typedef enum {
     kAbort,
     kContinue
   } lc_AuthenticateStatus;

   typedef std::tr1::function<lc_AuthenticateStatus (const string &msg)> AuthenticateNotifyFunc;

   bool Authenticate(lc_AuthenticateParams &params,
                     AuthenticateNotifyFunc notifyFunc);
}

在托管的 c++ 项目中,我试图定义一个参数以传递给上述函数:

public ref class Form1 : public System::Windows::Forms::Form
{
    public:
    lc_Authenticate::lc_AuthenticateStatus UpdateStatus(const string &msg)
    {
        <<DO SOMETHING>>
        return(lc_Authenticate::kContinue);
    }
    void test()
    {
        string appKey, appSecret;
        appKey = GetString(this->appKeyTextBox->Text);
        appSecret = GetString(this->appSecretTextBox->Text);

        lc_Authenticate dbauth;
        lc_AuthenticateParams params(appKey, appSecret);

        //  DOESN'T COMPILE won't let me take address of member function
        // or know about _1
        lc_Authenticate::AuthenticateNotifyFunc func =
            std::tr1::bind(&Form1::UpdateStatus, this, _1);

        dbauth.Authenticate(params, func);
    }
};

所以我试图实现一个将函数传递给 c++ 方法的通用方法,它不关心传递的函数是静态函数还是成员函数。而且我不清楚如何从托管代码中做到这一点。

【问题讨论】:

标签: c++ .net c++11 c++-cli tr1


【解决方案1】:

您不能通过设计绑定到托管类的实例方法。垃圾收集器在压缩堆时移动对象,导致 this 发生变化。您需要使用托管委托。所以你不能避免一个本地帮助类,它为你的函数提供你需要的稳定回调。您可以使用 Marshal::GetFunctionPointerForDelegate() 从那里返回托管代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多