将 CreateThread 与 lambda 一起使用 [英] Use CreateThread with a lambda

查看:40
本文介绍了将 CreateThread 与 lambda 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是在试验,但我想知道是否可以使此代码工作(如在编译中):

Just experimenting, but I was wondering if it's possible to make this code work (as in compile):

void main() {
    int number = 5;

    DWORD(*dontThreadOnMe)(PVOID) = [](PVOID data) {
        int value = *(int*) data;

        cout << value << endl;
        cout << "This callback executed successsfully" << endl;
    };

    CreateThread(NULL, NULL, dontThreadOnMe, &number, NULL, NULL);
    cin.get();
}

我有一个烦人的怀疑,因为 LPTHREAD_START_ROUTINE 回调的标准签名是 DWORD WINAPI Callback(PVOID) 我将无法编译没有添加的(但在语法上是非法的)WINAPI 标记.说到这里,WINAPICALLBACK(比如 WndProc)属性究竟是什么?我从来没有真正理解为什么在某些情况下你可以在一个函数上有多个属性.

I have this nagging suspicion that because the standard signature for a LPTHREAD_START_ROUTINE callback is DWORD WINAPI Callback(PVOID) I won't be able to get this to compile without the added (but grammatically illegal) WINAPI tag. Speaking of which, what exactly are the WINAPI and CALLBACK (for say WndProc) attributes? I've never really understood why in certain circumstances you could have multiple attributes on a function.

推荐答案

实际上这在 Visual C++ 2012 及更高版本中是可行的;引用 Microsoft 的 C++ 功能支持列表:

Actually this is possible with Visual C++ 2012 and above; to quote from Microsoft's list of C++ feature support:

此外,在 Visual Studio 2012 中的 Visual C++ 中,无状态 lambda可以转换为函数指针....我们已经实现了无状态可转换为具有任意调用的函数指针的 lambda公约.当您使用期望的 API 时,这一点很重要__stdcall 函数指针之类的东西

Additionally in Visual C++ in Visual Studio 2012, stateless lambdas are convertible to function pointers. ... we've made stateless lambdas convertible to function pointers that have arbitrary calling conventions. This is important when you are using APIs that expect things like __stdcall function pointers

因此在 Visual C++ 2012 中,您可以执行以下操作:

So in Visual C++ 2012 you can do something like:

unsigned int id;
HANDLE hThread = reinterpret_cast<HANDLE>(_beginthreadex(0, 0,
    [](void* pData) -> unsigned int {
        // I'm a thread!
        return 0;
    }, pThreadData, 0, &id));

这意味着您还可以将 lambda 与其他需要回调函数的 API 函数一起使用(例如,EnumWindows()CreateDialogParam() 之类的东西).

This means you can also use lambdas with other API functions that expect callback functions (things like EnumWindows() and CreateDialogParam(), for example).

这篇关于将 CreateThread 与 lambda 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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