2012-07-09 100 views
4

我試圖讓SWIG識別一個簡單的預處理器宏,它可以根據另一個定義和更復雜的函數「定義」一個新函數。所以,在C頭文件,我有:SWIG中的預處理器宏

#define FOO 1 
#define my_macro_fun(args) my_fun(args,FOO) 

痛飲看到併成功包裝my_fun,但我想它來包裝my_macro_fun代替。

回答

4

SWIG試圖發現macros that are constants幷包裝它們,但它不能用這樣的宏做任何聰明的事情。幸運的是,這有一個簡單的解決方法。假設你有下面的頭文件:

#define FOO 1 
#define my_macro_fun(args) my_fun(args,FOO) 

void my_fun(int a, int b); 

你可以用它喜歡:

%module test 
%{ 
#include "test.h" 
%} 

%include "test.h" 

其跳過my_macro_fun功能。爲了讓SWIG來包裝,雖然所有你需要做的是:

%module test 
%{ 
#include "test.h" 
%} 

// Lie! Tell SWIG that it should be wrapped like any other function. 
void my_macro_fun(int); 

// This is entirely optional: it will cause my_fun to be wrapped as well 
%include "test.h" 

這個小謊言是完全沒有在痛飲 - 它會產生假設my_macro_fun(int)是調用包裝代碼,就像你會如果你使用宏。在編譯包裝器時,編譯器最終會使用宏,沒有人比較聰明。

請注意,順序非常重要 - 宏的功能需要在接口文件中的%include之前,否則SWIG將在解析聲明時嘗試擴展宏,從而導致語法錯誤。您可以完全跳過%include,也可以使用%ignore,如果您想將其包含在其他零件中,但在生成的接口中抑制原始my_fun


隨着夜風一些語言(例如Python的),你也可以use the typemap default

%module test 
%{ 
#include "test.h" 
%} 

%typemap(default) int b { 
    $1 = FOO; 
} 

%include "test.h" 

要如果沒有,給出了它的參數提供一個值。