C ++函数作为函数指针 [英] C++ functor as a function pointer

查看:248
本文介绍了C ++函数作为函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Functor,我需要发送到一个函数接收一个函数指针作为参数(如 CreateThread )。

I have a Functor which I need to send to a function which receives a function pointer as a parameter (such as CreateThread).

我可以将它转换为静态方法地址吗?如果没有,我该怎么办呢?

Can I convert it to a static method address somehow? And if not, how can I do it?

推荐答案

不,不能将类类型的对象转换为函数指针。

No, you can't convert a class-type object to a function pointer.

但是,您可以编写一个非成员包装器函数来调用正确实例上的成员函数。许多API,包括 CreateThread ,允许你提供一个指针,当它调用你的回调( CreateThread ,这是 lpParameter 参数)。例如:

However, you can write a non-member wrapper function that calls the member function on the right instance. Many APIs, including CreateThread, allow you to provide a pointer that it will give back to you when it calls your callback (for CreateThread, this is the lpParameter parameter). For example:

DWORD WINAPI FunctorWrapper(LPVOID p)
{
    // Call operator() on the functor pointed to by p:
    return (*static_cast<FunctorType*>(p))();
}

// Used as:
FunctorType f;
CreateThread(0, 0, &FunctorWrapper, &f, 0, 0);

这篇关于C ++函数作为函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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