Swig a subset of C module while ignoring the rest of the module with other dependencies

时间:2015-07-08 15:59:57

标签: python c swig

I have a my.c file that defines function "foo" and "bar", where "foo" is standalone by itself and "bar" calls other functions, say "gee", defined in a bunch of other files that I don't want to be swigged.

Now I want to use Swig to wrap "foo" from my.c, without involving other files or functions. I defined a swig interface for foo:

%module sample                                                                                       
%{                                                         
/* Put headers and other declarations here */                                                       
extern float    foo();                                            
%}                                                                                                             
extern float    foo();

I was able to build the _my.so library, but when I try to call "foo" from python, it says:

ImportError: _my.so: undefined symbol: "gee".

And if I remove the definition of "bar" from my.c, the whole thing works.

Is there a way to tell swig to ignore "bar" and "gee"? I even tried to add "%ignore bar;" and "%ignore gee;" in the interface, and they don't solve the issue.

Thanks!

1 个答案:

答案 0 :(得分:0)

您可以在my.c文件中使用条件编译:

foo() {
   // foo stuff
}
#if !defined(COMPILING_FOR_SWIG)
bar() {
   gee();
}
#endif

然后在构建my.c时,请确保将编译器设置更新为#define COMPILING_FOR_SWIG,例如通常添加编译器选项-DCOMPILING_FOR_SWIG。这将确保编译器忽略bar()函数。

(请注意,COMPILING_FOR_SWIG是一个完全任意的名称,可以更改为您选择的其他名称)