c++ - 如何在 C++ 中使用 C 空括号函数?

标签 c++ c gcc

我有一个使用这个函数原型(prototype)C 库,我想在C++ 中使用它

int mlx_key_hook(void *win_ptr, int (*funct_ptr)(), void *param);

但实际上要求的功能是

int funct_ptr(int keycode, void *param);

事实上我有这个问题:Why put void in params?

那么,我问你如何用适当的 C++ funct_ptr 调用这个函数?

或者我是否需要在更改funct_ptr 原型(prototype) 后重新编译这个库?

这行不通:

mlx_key_hook(win_ptr, [](int keycode, void *param) -> int {

    return 0;

}, NULL);

这行得通,但这不是我想要的:

mlx_key_hook(win_ptr, []() -> int {

    return 0;

}, NULL);

最佳答案

最好的解决方案是重新编译您的 C++ 代码,并带有一个使用适当函数原型(prototype)的 header ,即

int mlx_key_hook(void *win_ptr, int (*funct_ptr)(int keycode, void *param), void *param);

然后带有带有两个参数的 lambda 的代码片段将被编译。

另一种解决方案是使用 reinterpret_cast。尽管不允许调用具有重新解释的签名(未定义行为)的函数,但在允许调用之前将重新解释的指针转换回其原始签名。

typedef int (*funct_ptr_good)(int, void *);
typedef int (*funct_ptr_bad)();

void foo(funct_ptr_bad fb) {
    // This is a C++ version of what your C library does
    funct_ptr_good fg = reinterpret_cast<funct_ptr_good>(fb);
    fg(12345, NULL);
}

int main() {
    funct_ptr_good fg = [] (int key, void * ptr) -> int {
        cout << key << " " << ptr << endl;
        return 0;
    };
    // foo expects a pointer that takes no parameters, in the same way that your C library does
    foo(reinterpret_cast<funct_ptr_bad>(fg));
    return 0;
}

以上打印 12345 0 ( demo )。

关于c++ - 如何在 C++ 中使用 C 空括号函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27588916/

相关文章:

c++ - 从 C++ 应用程序打开 Objective-C 窗口

c++ - 使用 std::min 将迭代器值钳制到 end()

c++ - 关于 Visual C++ 中的编译错误

c++ - 同时写入内存和磁盘

C: 使用 8 位的 char 作为一个完整的 int

objective-c - 使用 GCC 编译 *.mm

c++ - 如何等待 fork() 调用的所有子进程完成?

c++ - 如何将指针地址转换为无符号字符数组?

c - 结构类型数组

c - 使用不等于时无限循环 "for"