gpt4 book ai didi

windows - C++/CLI 中的错误,除非使用 Pthread 创建委托(delegate)实例,否则无法获取函数地址

转载 作者:可可西里 更新时间:2023-11-01 11:13:49 25 4
gpt4 key购买 nike

我在 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
}

Error 13 error C3374: can't take address of 'Tester::Test::LoginAccounts' unless creating delegate instance

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

 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 类。您仍然需要创建错误消息所提示的委托(delegate),委托(delegate)是函数指针的托管等价物。随着铃声的响起,它们不仅存储函数地址,而且还包装对象指针。使代码看起来类似于:

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 引用来做 hokeypokey。

如果您真的非常想使用 pthread,那么请使用 Marshal::GetFunctionPointerForDelegate() 将委托(delegate)转换为可以传递给 native 代码的指针。当心,您必须自己保留引用的委托(delegate)对象。垃圾收集器看不到 native 代码持有的引用。如果不固定,您仍然无法通过this。这些是非常丑陋的细节,您可以通过简单地使用 Thread 类来避免。

关于windows - C++/CLI 中的错误,除非使用 Pthread 创建委托(delegate)实例,否则无法获取函数地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com