C++/CLI 中出错,除非使用 Pthread 创建委托实例,否则无法获取函数地址



我在Visual C++2008 Professional上使用C++/CLI,由于我使用的是Windows窗体,这意味着我已经管理了代码,我正在尝试调用静态函数LoginAccounts,但我遇到了一个错误,可能是因为我将托管代码和非托管代码混合在一起,但我不知道该怎么办。我正在使用Windows 的PThread

System::Void testing_Click(System::Object^  sender, System::EventArgs^  e) {
    pthread_create(&t, NULL, &Contas::LoginAccounts, this); //Error in this line
}

错误13错误C3374:除非创建委托实例,否则无法获取"测试者::登录帐户"的地址

我该怎么办才能解决这个问题?这可能是一个简单的解决方案,但我想不通。提前谢谢。

 void LoginAccounts(){
    this->btn_next->Enabled = false;
    this->login_accounts->Enabled = false; //Unhandled exception here
     if(this->clb_contas->CheckedItems->Count <= 0){ //Unhandled exception here
         } 
}
System::Void testing_Click(System::Object^  sender, System::EventArgs^  e) {
    ThreadStart^ start = gcnew ThreadStart(this, &Login::LoginAccounts);
                Thread^ t = gcnew Thread(start);
                t->Start();
        }

如果您只想调用托管代码,那么使用pthreads是没有意义的。请改用System::Threading::Thread类。您仍然需要创建错误消息所抱怨的委托,委托是函数指针的托管等价物。当bells打开时,它们不仅存储函数地址,还封装对象指针。让代码看起来像这样:

using namespace System::Threading;
...
private: 
    void LoginAccounts() {
        // etc...
    }
    System::Void testing_Click(System::Object^  sender, System::EventArgs^  e) {
        ThreadStart^ start = gcnew ThreadStart(this, &Form1::LoginAccounts);
        Thread^ t = gcnew Thread(start);
        t->Start();
    }

请注意LoginAccounts()在这里是一个实例方法,无需对this引用进行恶作剧。

如果您真的、真的想使用pthreads,那么可以使用Marshal::GetFunctionPointerForDelegate()将委托转换为可以传递给本机代码的指针。请注意,您必须自己引用代理对象。垃圾收集器无法查看本机代码所持有的引用。而且你仍然无法在没有固定的情况下通过这个。这些都是非常丑陋的细节,您可以通过简单地使用Thread类来避免。

请参阅我对您另一个问题的回答,即从Windows窗体类调用PThread到Windows窗体类中的函数。您可以使用这里详细介绍的相同原理。

最新更新