将函数指针作为参数从 C 代码传递到 C++ 函数的正确方法是什么?简单示例:
foo_c.h
typedef int (*int_func)(int);
extern void foo(int_func);
foo.h
#ifdef __cplusplus
extern "C" {
#endif
#include "foo_c.h"
void foo(int_func);
#ifdef __cplusplus
}
#endif
foo.cpp
#include "foo.h"
#include <iostream>
void foo(int_func)
{
std::cout << "foo : int_func(5) : " << int_func(5) << std::endl;
}
main.c
#include <stdio.h>
#include "foo_c.h"
int timestwo(int x)
{
return x*2;
}
int main()
{
foo(timestwo);
return 0;
}
生成文件
all: main.c libfoo.so
gcc main.c -L`pwd` -lfoo
libfoo.so: foo.cpp foo.h foo_c.h
g++ -fPIC -shared -o libfoo.so foo.cpp
clean:
rm -rf a.out libfoo.so
此代码编译并运行,但得到不正确的输出:
foo : int_func(5) : 1
这是怎么回事?
最佳答案
这段代码:
void foo(int_func)
您有一个变量类型但没有名称,并且您没有调用该函数。
将其更改为:
void foo(int_func myfunc)
如果您向函数添加了一些调试输出,您就会意识到您的函数没有被调用:
int timestwo(int x)
{
std::cout << "timestwo(" << x << ")" << std::endl;
return x*2;
}
在你的版本中,输出没有发生,所以函数没有被调用,所以 int_func 没有被解释为函数。
关于c++ - 将函数指针作为参数从 C 代码传递到 C++ 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29441933/