gpt4 book ai didi

c++ - 在 C++ 程序中调用 C 函数

转载 作者:行者123 更新时间:2023-11-28 06:57:27 25 4
gpt4 key购买 nike

我正在使用一个 C 库,它有一个需要 C 函数指针的 API。

是否可以为这个函数指针传递一个C++类成员函数?

这是 C API:

typedef int (*WRITE_FUNC_T)(void *d, char *buffer, int n);

void start(WRITE_FUNC_T callback);

class MyClass {
public:
int mycallback(void *d, char *buffer, int n);
}

我想将 MyClass::mycallback 传递给 start()。当我这样做时,出现编译错误,提示类型参数不匹配。

最佳答案

这对我有用:

#include <iostream>
#include <sstream>

typedef int (*WRITE_FUNC_T)(void *d, char *buffer, int n);

void start(WRITE_FUNC_T callback) {}

class MyClass {
public:
int mycallback(char *buffer, int n) {
return 0;
}
static int newcallback(void *d, char *buffer, int n) {
return static_cast<MyClass*>(d)->mycallback(buffer, n);
}
};

int main() {
start(&MyClass::newcallback);
}

关于c++ - 在 C++ 程序中调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com