将函数指针作为参数从 C 代码传递到 C++ 库
Passing a function pointer from C code to a C++ library as an argument
将函数指针作为参数从 C 代码传递到 C++ 函数的正确方法是什么?简单的例子:
foo_c.h
typedef int (*int_func)(int);
extern void foo(int_func);
福.H
#ifdef __cplusplus
extern "C" {
#endif
#include "foo_c.h"
void foo(int_func);
#ifdef __cplusplus
}
#endif
傅.cpp
#include "foo.h"
#include <iostream>
void foo(int_func)
{
std::cout << "foo : int_func(5) : " << int_func(5) << std::endl;
}
主.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未被解释为函数。
你的问题在这里:
void foo(int_func)
{
std::cout << "foo : int_func(5) : " << int_func(5) << std::endl;
}
您没有调用该函数。
将其更改为:
void foo(int_func fn)
{
std::cout << "foo : int_func(5) : " << fn(5) << std::endl;
}
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值