問題描述
我正在使用 C 庫開發(fā) C++ 應用程序.我必須向 C 庫發(fā)送一個指向函數的指針.
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.
有人可以幫忙嗎?
推薦答案
如果我沒記錯的話,只有類的靜態(tài)方法可以通過指向函數語法的普通"C 指針訪問.所以盡量讓它靜態(tài).指向類的方法的指針需要額外的信息,例如對象"(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.
這篇關于將 C++ 函數指針轉換為 c 函數指針的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!