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语言明确支持和理解的思想.
由于C中没有为任何函数类型定义调用约定,因此无法显式传回C函数.您只能传回C函数(那些用extern“C”明确声明的函数)并保证它们是兼容的.
像所有未定义的行为一样,这似乎有效(比如传回正常的C函数或静态成员).但是像所有未定义的行为一样,它被允许工作.你可以;保证它实际上是正确的或便携的.
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
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++ seemingly lets me use all of the above,
是.但它假设您传递给使用C编译器构建的对象(这将是合法的).因为C代码将使用正确的调用约定.问题是当你将这些东西传递给C库时(pthreads会浮现在脑海中).