c++ - 什么样的 C++ 函数可以放在 C 函数指针中?

标签 c++ function-pointers calling-convention language-binding extern-c

我有一个 C 库,它使用函数指针结构进行回调。将从 C 代码调用回调。

extern "C" {
typedef struct callbacks_t {
    void (*foo) (const char*);
    int  (*bar) (int);  
} callbacks_t;
}// extern C

我可以安全将哪些类型的 C++ 函数放在那些函数指针中,以便从 C 库中调用?静态成员函数?完全指定的模板函数?非捕获 Lambda?

g++ 似乎让我可以使用上述所有功能,但我质疑将不同的调用约定和语言绑定(bind)用于 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 明确支持和理解的东西。

由于 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 突然想到)。

关于c++ - 什么样的 C++ 函数可以放在 C 函数指针中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36941866/

相关文章:

c++ 转换与 if_then_else 控制结构

c++ - 在 Windows C++ 中更改控制台代码页

c - 函数指针类型

c++ - 最令人烦恼的解析困惑

c - X86-64 NASM 调用 extern c 函数

c++ - 在 C++ 中评估数学表达式

c++ - 关于 C/C++ 解引用运算符

c++ - 关于在 winsock 的 addrinfo 结构中使用智能指针的问题

c++ - 如何在一个 vs2008 项目中将库与 __stdcall 和 __cdecl 结合起来

cobol - CALL 语句中的 BY CONTENT 和 BY VALUE 有什么区别?