C++ 将函子作为函数指针传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1840029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing functor as function pointer
提问by dagw
I'm trying to use a C library in a C++ app and have found my self in the following situation (I know my C, but I'm fairly new to C++). On the C side I have a collection of functions that takes a function pointer as their argument. On the C++ side I have objects with a functor which has the same signature as the function pointer needed by the C function. Is there any way to use the C++ functor as a function pointer to pass to the C function?
我正在尝试在 C++ 应用程序中使用 C 库,并且发现自己处于以下情况(我知道我的 C,但我对 C++ 还很陌生)。在 C 端,我有一个函数集合,它们以函数指针作为参数。在 C++ 方面,我有一个带有函子的对象,该函子与 C 函数所需的函数指针具有相同的签名。有什么办法可以使用C++函子作为函数指针传递给C函数吗?
回答by Tomek Szpakowicz
You cannot directly pass a pointer to a C++ functor object as a function pointer to C code (or even to C++ code).
您不能直接将指向 C++ 函子对象的指针作为指向 C 代码(甚至 C++ 代码)的函数指针传递。
Additionally, to portably pass a callback to C code it needs to be at least declared
as an extern "C"
non-member function.
At least, because some APIs require specific function call conventions and thus
additional declaration modifiers.
此外,要将回调可移植地传递给 C 代码,它至少需要声明extern "C"
为非成员函数。至少,因为某些 API 需要特定的函数调用约定,因此需要额外的声明修饰符。
In many environments C and C++ have the same calling conventions and differ only
in name mangling, so any global function or static member will work.
But you still need to wrap the call to operator()
in a normal function.
在许多环境中,C 和 C++ 具有相同的调用约定,仅在名称修改方面有所不同,因此任何全局函数或静态成员都可以使用。但是您仍然需要将调用包装operator()
在一个普通函数中。
If your functor has no state (it is an object just to satisfy some formal requirements etc):
class MyFunctor { // no state public: MyFunctor(); int operator()(SomeType ¶m) const; }
you can write a normal extern "C" function which creates the functor and executes its operator().
extern "C" int MyFunctorInC(SomeType *param) { static MyFunctor my_functor; return my_functor(*param); }
If your functor has state, eg:
class MyFunctor { // Some fields here; public: MyFunctor(/* some parameters to set state */); int operator()(SomeType ¶m) const; // + some methods to retrieve result. }
andthe C callback function takes some kind of user state parameter (usually void *):
void MyAlgorithmInC(SomeType *arr, int (*fun)(SomeType *, void *), void *user_state);
you can write a normal extern "C" function which casts its state parameter to your functor object:
extern "C" int MyFunctorInC(SomeType *param, void *user_state) { MyFunctor *my_functor = (MyFunctor *)user_state; return (*my_functor)(*param); }
and use it like this:
MyFunctor my_functor(/* setup parameters */); MyAlgorithmInC(input_data, MyFunctorInC, &my_functor);
Otherwise the only normal way to do it (normal as in "without generating machine code at runtime" etc.) is to use some static (global) or thread local storage to pass the functor to an extern "C" function. This limits what you can do with your code and is ugly but will work.
如果您的函子没有状态(它只是满足一些形式要求等的对象):
class MyFunctor { // no state public: MyFunctor(); int operator()(SomeType ¶m) const; }
您可以编写一个普通的 extern "C" 函数来创建函子并执行其 operator()。
extern "C" int MyFunctorInC(SomeType *param) { static MyFunctor my_functor; return my_functor(*param); }
如果您的函子有状态,例如:
class MyFunctor { // Some fields here; public: MyFunctor(/* some parameters to set state */); int operator()(SomeType ¶m) const; // + some methods to retrieve result. }
并且C 回调函数采用某种用户状态参数(通常为 void *):
void MyAlgorithmInC(SomeType *arr, int (*fun)(SomeType *, void *), void *user_state);
您可以编写一个普通的 extern "C" 函数,将其状态参数转换为您的函子对象:
extern "C" int MyFunctorInC(SomeType *param, void *user_state) { MyFunctor *my_functor = (MyFunctor *)user_state; return (*my_functor)(*param); }
并像这样使用它:
MyFunctor my_functor(/* setup parameters */); MyAlgorithmInC(input_data, MyFunctorInC, &my_functor);
否则,唯一的正常方法(如“在运行时不生成机器代码”等中的正常方法)是使用一些静态(全局)或线程本地存储将函子传递给外部“C”函数。这限制了你可以用你的代码做的事情,虽然丑陋但可以工作。
回答by Andreas Brinck
回答by Alexey Malistov
No, of course. The signature of your C function take an argument as function.
不,当然。C 函数的签名将参数作为函数。
void f(void (*func)())
{
func(); // Only void f1(), void F2(), ....
}
All tricks with functors are used by templatefunctions:
模板函数使用函子的所有技巧:
template<class Func>
void f (Func func)
{
func(); // Any functor
}
回答by Michael Burr
A C callback function written in C++ must be declared as an extern "C"
function - so using a functor directly is out. You'll need to write some sort of wrapper function to use as that callback and have that wrapper call the functor. Of course, the callback protocol will need to have some way of passing context to the function so it can get to the functor, or the task becomes quite tricky. Most callback schemes have a way to pass context, but I've worked with some brain-dead ones that don't.
用 C++ 编写的 AC 回调函数必须声明为extern "C"
函数——所以直接使用函子是不行的。您需要编写某种包装器函数来用作该回调,并让该包装器调用函子。当然,回调协议需要有某种方式将上下文传递给函数,以便它可以到达函子,否则任务就会变得非常棘手。大多数回调方案都有传递上下文的方法,但我已经使用了一些没有的脑死的方法。
See this answer for some more details (and look in the comments for anecdotal evidence that the callback must be extern "C"
and not just a static member function):
有关更多详细信息,请参阅此答案(并在评论中查看有关回调必须是extern "C"
而不仅仅是静态成员函数的轶事证据):
回答by UncleBens
I don't think you can: operator()
in a function object is really a member function, and C doesn't know anything about those.
我认为你不能:operator()
在一个函数中,对象实际上是一个成员函数,而 C 对此一无所知。
What you should be able to use are free C++ functions, or static functions of classes.
您应该能够使用的是免费的 C++ 函数或类的静态函数。
回答by user3996901
GCC allows you to convert member function pointers to plain function pointers (the first argument of the function called by the plain function pointer then is this
).
GCC 允许您将成员函数指针转换为普通函数指针(由普通函数指针调用的函数的第一个参数是this
)。
Check out the respective link in the manual.
This requires the -Wno-pmf-conversions
flag in order to silence the respective warning for the decidedly non-standard feature. Very convenient for interfacing C style libraries with C++ style programming. When the member function pointer is a constant, this does not even need to generate any code at all: the API would use that argument order anyway.
这需要-Wno-pmf-conversions
标志,以便使对于绝对非标准功能的相应警告静音。将 C 风格库与 C++ 风格编程相连接非常方便。当成员函数指针是一个常量时,它甚至根本不需要生成任何代码:API 无论如何都会使用该参数顺序。
If you already have a functor, flattening the functor in that manner will likely mean flattening its operator()
, giving you a function that has to be called with a functor class pointer itself as its first argument. Which does not necessarily help all that much but at least has C linkage.
如果您已经有一个函子,以这种方式展平函子可能意味着展平它的operator()
,从而为您提供一个必须使用函子类指针本身作为其第一个参数来调用的函数。这不一定有多大帮助,但至少有 C 链接。
But at least when you are not going through functors this is helpful and provides a no-nonsense C linkage replacement for std::mem_fn
from <functional>
.
但至少当您不使用函子时,这很有帮助,并为std::mem_fn
from提供了一个严肃的 C 链接替代<functional>
。
回答by JoeG
Many C APIs that take function pointer callbacks have a void* parameter for user state. If you've got one of those, you're in luck - you can use an exterm C function that treats the user data as some sort of reference or key to lookup the functor, then execute it.
许多采用函数指针回调的 C API 都有一个用于用户状态的 void* 参数。如果您有其中之一,那么您很幸运 - 您可以使用 exterm C 函数将用户数据视为某种引用或键来查找函子,然后执行它。
Otherwise, no.
否则,没有。
回答by Tim Ebenezer
It depends if this is a static or instance method, if it is static then you can pass through the function as className::functionName, if it is an instance method it is fair more complicated, because you obviously need to tie to a certain instance but can't do it in the same way as you would with delegates in C# etc.
这取决于这是一个静态方法还是实例方法,如果它是静态的,那么您可以将函数作为 className::functionName 传递,如果它是一个实例方法则更复杂,因为您显然需要绑定到某个实例但不能像在 C# 等中使用委托那样做。
The best way I've found of doing this is to create a holding class which is instantiated with the instance of the object as well as the function pointer, the holding class can then invoke the function directly.
我发现这样做的最好方法是创建一个使用对象实例和函数指针实例化的保持类,然后保持类可以直接调用该函数。
回答by Charles Salvia
I would say no, because a C++ functor has an overloaded operator ()
which is a member function, and would thus require a member function pointer. This is a totally different data type than a normal C function pointer, since it cannot be invoked without an instance of the class. You'd need to pass a normal function or a static member function to the C library. Since an overloaded ()
operator can't be static, you can't do it. You'd need to pass the C-library a normal, non-member function or static member function, from which you can then invoke the C++ functor.
我会说不,因为 C++ 函子有一个重载运算符()
,它是一个成员函数,因此需要一个成员函数指针。这是一种与普通 C 函数指针完全不同的数据类型,因为它不能在没有类实例的情况下被调用。您需要将普通函数或静态成员函数传递给 C 库。由于重载()
运算符不能是静态的,因此您不能这样做。您需要向 C 库传递一个普通的非成员函数或静态成员函数,然后您可以从中调用 C++ 函子。
回答by Bj?rn Pollex
Hm, maybe you could write a free template function that wraps around your function-objects. If they all have the same signature, this should work. Like this (not tested):
嗯,也许你可以编写一个免费的模板函数来包装你的函数对象。如果它们都具有相同的签名,这应该可以工作。像这样(未测试):
template<class T>
int function_wrapper(int a, int b) {
T function_object_instance;
return funcion_object_instance( a, b );
}
This would do for all function that take two ints and return an int.
这适用于所有需要两个整数并返回一个整数的函数。