c++ - 将函数指针作为参数从 C 代码传递到 C++ 库

标签 c++ c function

将函数指针作为参数从 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;
}

ma​​in.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/

相关文章:

jquery - 同时使用两个 jquery 函数

c - C 中返回字符串的函数。为什么返回 null?

c++ - 函数指针基础问题

c++ - 代码 `[&]()` 在 C++ 中意味着什么?

c - 如何知道哪个线程正在执行一个函数?

c - 使用 execl 复制调用可执行文件时提供的两个文件

c++ - 将(部分)模板化模板函数作为 std::function(或函数指针)传递

c++ - 为什么 C++ 在除法时不返回 double?

C - 按字符数组字段对结构数组进行排序

jquery - 从 jQuery 函数返回值