可以在C函数指针中放置哪些C ++函数? [英] What kinds of C++ functions can be placed in a C function pointer?
问题描述
我有一个C库,该库使用函数指针的结构进行回调.回调将从C代码中调用.
I have a C library that uses a struct of function pointers for callbacks. The callbacks will be called from C code.
extern "C" {
typedef struct callbacks_t {
void (*foo) (const char*);
int (*bar) (int);
} callbacks_t;
}// extern C
我可以安全将哪些类型的C ++函数放在要从C库中调用的那些函数指针中?静态成员函数?完全指定的模板功能?不捕获Lambda?
What kinds of C++ functions can I safely place in those function pointers to be called from the C library? Static member functions? Fully specified template functions? Non-capturing Lambdas?
g ++似乎可以让我使用以上所有内容,但是我对C和C ++函数使用不同的调用约定和语言绑定时的安全性表示怀疑.
g++ seemingly lets me use all of the above, but I question the safety when different calling conventions and language bindings are used for C and C++ functions.
推荐答案
我有一个C库,该库使用函数指针的结构进行回调.回调将从C代码中调用.
I have a C library that uses a struct of function pointers for callbacks. The callbacks will be called from C code.
C库仅能理解C.因此,您只能传递C明确支持和理解的内容.
A C library only understands C. So you can only pass back things that are explicitly supported and understood by C.
由于C ++中没有定义任何函数类型的调用约定,因此您不能显式地传回C ++函数.您只能传回C函数(用extern "C"
明确声明的C函数)并保证它们兼容.
Since there is no definition of calling conventions for any function types in C++ you can not explicitly pass back C++ functions. You can only pass back C function (those explicitly declared with extern "C"
) and guarantee that they are compatible.
就像所有未定义的行为一样,这似乎可以正常工作(例如,回传普通的C ++函数或静态成员).但是,像所有未定义的行为一样,它也可以工作.您只是不能保证它实际上是正确的或可移植的.
Like all undefined behavior this may seem to work (like passing back normal C++ functions or static members). But like all undefined behavior it's allowed to work. You just can't guarantee that it's actually correct or portable.
extern "C" {
typedef struct callbacks_t {
void (*foo) (const char*);
int (*bar) (int);
} callbacks_t;
// Any functions you define in here.
// You can set as value to foo and bar.
}// extern C
我可以安全地将哪些C ++函数放置在要从C库中调用的那些函数指针中?
What kinds of C++ functions can I safely place in those function pointers to be called from the C library?
静态成员函数?
不.但这恰好适用于许多平台.这是一个常见的错误,会在某些平台上咬人.
No. But this happens to work on a lot of platforms. This is a common bug and will bite people on some platforms.
完全指定的模板功能?
Fully specified template functions?
不.
没有捕获的Lambda?
Non-capturing Lambdas?
否.
g ++似乎可以让我使用以上所有内容,
g++ seemingly lets me use all of the above,
是的.但是,假设您要传递使用C ++编译器构建的对象(这是合法的).由于C ++代码将使用正确的调用约定.问题是,当您将这些东西传递给C库时(就会想到pthreads).
Yes. But it is assuming that you are passing to objects that are built with the C++ compiler (which would be legal). As C++ code will use the correct calling convention. The problem is when you pass these things to a C library (pthreads springs to mind).
这篇关于可以在C函数指针中放置哪些C ++函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!