将 C++ 函数指针转换为 c 函数指针

2021-12-13 00:00:00 pointers c function-pointers c++

我正在使用 C 库开发 C++ 应用程序.我必须向 C 库发送一个指向函数的指针.

I am developing a C++ application using a C library. I have to send a pointer to function to the C library.

这是我的课:

 class MainWindow : public QMainWindow {  
     Q_OBJECT  
     public:  
     explicit MainWindow(QWidget *parent = 0);  
     private:  
     Ui::MainWindow *ui;
     void f(int*);

 private slots:
     void on_btn_clicked(); 
};

这是我的 on_btn_clicked 函数:

This is my on_btn_clicked function:

void MainWindow::on_btn_clicked()
{
    void (MainWindow::* ptfptr) (int*) = &MainWindow::f;

    c_library_function(static_cast<void()(int*)>(ptfptr), NULL);

}

C 函数应该得到一个指向这样的函数的指针:void f(int*).但是上面的代码不起作用,我无法成功将我的 f 成员函数转换为所需的指针.

The C function should get a pointer to a such function : void f(int*). But the code above doesn't work, I cannot succeed to convert my f member function to the desired pointer.

有人可以帮忙吗?

推荐答案

如果我没记错的话,只有类的静态方法可以通过指向函数语法的普通"C 指针访问.所以尽量让它静态.指向类的方法的指针需要额外的信息,例如对象"(this)对于纯 C 方法没有意义.

If I recall it correctly, Only static methods of a class can be accessed via "normal" C pointer to function syntax. So try to make it static. The pointer to a method of a class needs extra information, such as the "object" (this) which has no meaning for a pure C method.

此处显示的常见问题有很好的解释和您的问题的可能(丑陋)解决方案.

The FAQ shown here has good explanation and a possible (ugly) solution for your problem.

相关文章