SWIG不会在包装文件中声明全局变量

时间:2012-07-30 12:19:39

标签: java swig

我正在使用Cent OS,SWIG 1.3,我已经测试过从SWIG示例编译示例Java示例。它包括:

example.c

/* A global variable */
double Foo = 3.0;

/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
  int g;
  g = y;
  while (x > 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
}

example.i

%module example

extern int gcd(int x, int y);
extern double Foo;

然后我使用命令:

swig -java example.i

然后我用:

编译生成的example_wrap.c
gcc -c example_wrap.c -I/usr/java/jdk1.6.0_24/include -I/usr/java/jdk1.6.0_24/include/linux

我有以下错误:

example_wrap.c: In function ‘Java_exampleJNI_Foo_1set’:
example_wrap.c:201: error: ‘Foo’ undeclared (first use in this function)

example.i文件是错误还是我没有完成某些事情?或者这是SWIG中的一个错误?有解决方法吗?

1 个答案:

答案 0 :(得分:4)

您告诉SWIG将声明函数和全局变量,但您需要确保在生成的包装器代码中可以看到声明。 (如果你没有use a higher warning setting for gcc,你也可能会收到gcd隐式声明的警告

解决方案是使声明可见,最简单的方法是:

%module example

%{
// code here is passed straight to example_wrap.c unmodified
extern int gcd(int x, int y);
extern double Foo;
%}

// code here is wrapped:
extern int gcd(int x, int y);
extern double Foo;

我个人会添加一个带有这些声明的example.h文件并生成模块文件:

%module example

%{
// code here is passed straight to example_wrap.c unmodified
#include "example.h"
%}

// code here is wrapped:
%include "example.h"

在example.c中使用相应的include来进行测量。

写这个的另一种方式是:

%module example

%inline %{
  // Wrap and pass through to example_wrap.c simultaneously
  extern int gcd(int x, int y);
  extern double Foo;  
%}

但通常我只建议使用%inline来处理你所包装的内容特定于包装过程而不是你要包装的库的一般部分。