2015-04-04 139 views
1

將函數指針從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 

這是怎麼回事?

回答

2

此代碼:

void foo(int_func) 

你有一個變量的類型,但沒有名字,你是不是調用該函數。

將其更改爲:

void foo(int_func myfunc) 

你就會意識到,如果你已經添加了一些調試輸出到它不會被調用你的函數:

int timestwo(int x) 
{ 
    std::cout << "timestwo(" << x << ")" << std::endl; 
    return x*2; 
} 

在您的版本的輸出沒有按」不會發生,所以函數沒有被調用,所以int_func不被解釋爲函數。

+0

清楚,原來是一個愚蠢的錯誤。謝謝 :) – spiffman 2015-04-04 02:43:06

1

你的問題是在這裏:

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; 
}