Frage

I'm new to threads and Winforms/C++. I would like to start a function in a new thread when I press a button. I was following this as a tutorial for threads. When I build the example code given on that site in a separate VC++ project, the build succeeds.

However, if I do the following in my C++/Winforms the build won't complete, I get a build error.

What am I missing here?

Help!

Code:

void  Test( void *arg );
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)
         {
                    _beginthread(Test, 0, (void*)12);
         }
void  Test( void *arg )
{
    // Do something
}

Build ERROR:

Error   1   error C2664: '_beginthread' : cannot convert parameter 1 from 'void (__clrcall *)(void *)' to 'void (__cdecl *)(void *)'    c:\users\documents\visual studio 2010\projects\statsv2.0\statsv2.0\Form1.h  659 1   StatsV2.0
War es hilfreich?

Lösung

You're using managed C++ (C++/CLR). This is very different from native C++ (which the tutorial was written for).

In managed C++, the default calling convention is not compatible with the calling convention of the function pointer that the native _beginthread function is expecting. Fortunately, managed C++ has very good interop with native C++, and changing your function declaration to the following should work:

void __cdecl Test( void *arg )

Since you're using managed C++, you have the full power of .NET on your side, and could instead create managed threads (e.g. with a Task object).

Note also that any win32 UI object created on the main thread must only be accessed on that thread -- so be careful! :-)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top