C ++ / Winforms线程:我得到一个生成错误与_beginthread [英] C++/Winforms threads: I get a build error with _beginthread

查看:360
本文介绍了C ++ / Winforms线程:我得到一个生成错误与_beginthread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触线程和Winforms / C ++。我想在一个新的线程中,当我按下一个按钮开始一个功能。我将此作为教程作为主题。当我在单独的VC ++项目中构建在该网站上给出的示例代码时,构建成功

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.

但是,如果我执行以下操作我的C ++ / Winforms版本将无法完成,我遇到构建错误

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

我在这里缺少什么?

帮助!

代码:

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
}

构建错误:

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


推荐答案

您正在使用托管C ++(C ++ / CLR)。这与本地C ++(本教程是为其编写的)非常不同。

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

在托管C ++中,默认调用约定与函数指针的调用约定不兼容原生 _beginthread 函数是期望的。幸运的是,托管C ++与原生C ++具有非常好的互操作性,并且将函数声明更改为以下内容:

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 )

由于您使用托管C ++,并且可以改为创建托管线程(例如,使用 Task 对象)。

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).

注意,在主线程上创建的任何win32 UI对象必须 只能在该线程上访问 - 请小心! : - )

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

这篇关于C ++ / Winforms线程:我得到一个生成错误与_beginthread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆