I’m using pthread on Windows Form in Visual Studio 2008 Professional, But I’m getting the error in the line that I show in the example source. Probably because it’s C++/CLI because this usually work in regular classes. The problem is in this line:
((TestGUI*)context)->TestxFunc();
in the function StaticCallFunc
public ref class TestGUI : public System::Windows::Forms::Form {
/...
public:
void TestxFunc(std::string test, std::string test2){
this->btn_next->Enabled = false;
cout << "HI, Test: " << test << "," << " Test 2: " << test2 << endl;
}
static void *StaticCallFunc(void *context){
std::string test = "foo";
std::string test2 = "bar";
printf("\nStarting Thread");
((TestGUI*)context)->TestxFunc(); //Line with the error down.
return 0;
}
System::Void tester_Click(System::Object^ sender, System::EventArgs^ e) {
pthread_t t;
pthread_create(&t, NULL, &TestGUI::StaticCallFunc, this);
}
//...
error C3699: ” : cannot use this indirection on type ‘Test::TestxFunc’ 1>
compiler replacing ‘*’ with ‘^’ to continue parsingerror C2227: left of ‘->TestxFunc’ must point to
class/struct/union/generic type
what do I do to fix this? This call usually work on regular classes, but inside the Windows Form it really doesn’t
Since
TestGUIis a CLI/C++ class, you should use the^not*to dereference its pointer, but thats not the only problem. It seems you want to execute a CLI/C++ class member method in a pthread. To make it work, you can try the following way:*Remove
StaticCallFuncfromTestGUIclass and make it a global method.*To pass
TestGUIpointer to an unmanaged function you can usegcroot. So define a container class e.g.PtrContainerwhich hasgcrootas a member.When you bind to
pthread_createyou can usePtrContaineras the following:And you should delete the container pointer inside the driver method (
StaticCallFunc) after you have done with it:One more note; when you are accessing a .NET gui component in a multithread way, you must be careful to make calls to your controls in a thread-safe way.
Edit: I have added the following complete source code which compiles and works under Visual Studio 11, Windows7.
Compiled with: