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

Passing a function pointer from C code to a C++ library as an argument

本文关键字:代码 C++ 指针 函数 参数      更新时间:2023-10-16

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