我试图让 SWIG 识别一个简单的预处理器宏,该宏基于另一个定义和更复杂的函数“定义”一个新函数。因此,在 C 头文件中,我有:
#define FOO 1
#define my_macro_fun(args) my_fun(args,FOO)
SWIG 看到并成功 wraps my_fun
,但我希望它改为 wrap my_macro_fun
。
SWIG 尝试找出常量宏并将它们包装起来,但它无法用这样的宏做任何聪明的事情。幸运的是,有一个简单的解决方法。假设您有以下头文件:
#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"
这个小谎言在 SWIG 中非常好——它会生成假设my_macro_fun(int)
是可调用的包装器代码,就像你使用宏时一样。编译包装器时,编译器最终会在那里使用宏,没有人更聪明。
请注意,顺序很重要 - 真正是宏的函数需要%include
位于接口文件中的 之前,否则 SWIG 将在解析您的声明期间尝试扩展宏,这会导致语法错误。您可以完全跳过%include
,或者%ignore
如果您想将它包含在其他部分但my_fun
在生成的界面中抑制原始部分,则也可以使用。
对于一些 SWIG 语言(例如 Python),您还可以使用 typemap default:
%module test
%{
#include "test.h"
%}
%typemap(default) int b {
$1 = FOO;
}
%include "test.h"
如果没有为参数提供值,则为参数提供值。