【发布时间】:2012-07-09 21:32:44
【问题描述】:
我试图让 SWIG 识别一个简单的预处理器宏,该宏基于另一个定义和更复杂的函数“定义”一个新函数。所以,在 C 头文件中我有:
#define FOO 1
#define my_macro_fun(args) my_fun(args,FOO)
SWIG 看到并成功包装了 my_fun,但我希望它改为包装 my_macro_fun。
【问题讨论】:
我试图让 SWIG 识别一个简单的预处理器宏,该宏基于另一个定义和更复杂的函数“定义”一个新函数。所以,在 C 头文件中我有:
#define FOO 1
#define my_macro_fun(args) my_fun(args,FOO)
SWIG 看到并成功包装了 my_fun,但我希望它改为包装 my_macro_fun。
【问题讨论】:
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"
这个小谎言在 SWIG 中非常好 - 它会生成假设 my_macro_fun(int) 是可调用的包装器代码,就像您使用宏时一样。编译包装器时,编译器最终会在那里使用宏,没有人比它更聪明。
请注意,顺序很重要 - 真正是宏的函数需要在接口文件中的 %include 之前出现,否则 SWIG 将在解析声明期间尝试扩展宏,这会导致语法错误。您可以完全跳过%include,或者如果您想将%ignore 包含在其他部分中,但在生成的界面中隐藏原始my_fun。
对于一些 SWIG 语言(例如 Python),您还可以use the typemap default:
%module test
%{
#include "test.h"
%}
%typemap(default) int b {
$1 = FOO;
}
%include "test.h"
如果没有为参数提供值,则为其提供值。
【讨论】: