將函數指針從C代碼傳遞給C++函數作爲參數的正確方法是什麼?簡單的例子:將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;
}
的Makefile
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
這是怎麼回事?
清楚,原來是一個愚蠢的錯誤。謝謝 :) – spiffman 2015-04-04 02:43:06