SWIG - 名称空间问题

7 投票
1 回答
10360 浏览
提问于 2025-04-16 04:03

我在用SWIG 1.3.40(我也试过1.3.31)时,遇到了一些麻烦,想让下面这个简单的例子正常工作。只要我不把Foo结构放在命名空间里,它就能作为一个Python模块正常使用,但一旦我加上命名空间,就会在生成的test_wrap.c文件中出现编译错误。

test.h:

#ifndef __TEST_H__
#define __TEST_H__

#define USE_NS 1

#if USE_NS
namespace ns {
#endif

struct Foo {
  float a;
  float b;
  float func();
};

#if USE_NS
}
#endif

#endif

test.cpp

#include "test.h"

#if USE_NS
namespace ns {
#endif

float Foo::func()
{
  return a;
}

#if USE_NS
}
#endif

test.i

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

%include "test.h"

我在OSX 10.6.3上运行以下命令来构建一个包:

swig -python test.i
g++ -c -m64 -fPIC test.cpp
g++ -c -m64 -fPIC -I/usr/local/include -I/opt/local/include -I/opt/local/Library/Frameworks/Python.framework/Headers test_wrap.c
g++ -o _test.so -bundle -flat_namespace -undefined suppress test_wrap.o test.o -L/usr/local/lib -L/opt/local/lib -lpython2.6

这样做是可以的,但前提是我去掉命名空间。我以为SWIG在这种简单的情况下会自动处理命名空间。那我到底哪里出错了呢?

这是我遇到的错误——看起来SWIG引用了一个'ns'和一个'namespace'符号,但它们是未定义的。

test_wrap.c: In function ‘int Swig_var_ns_set(PyObject*)’:
test_wrap.c:2721: error: expected primary-expression before ‘=’ token
test_wrap.c:2721: error: expected primary-expression before ‘namespace’
test_wrap.c:2721: error: expected `)' before ‘namespace’
test_wrap.c:2721: error: expected `)' before ‘;’ token
test_wrap.c: In function ‘PyObject* Swig_var_ns_get()’:
test_wrap.c:2733: error: expected primary-expression before ‘void’
test_wrap.c:2733: error: expected `)' before ‘void’

1 个回答

19

在你的 test.i 文件中,在 #include 之后加上一行 "using namespace ns"。如果不加这一行,你的 swig 包装代码就不知道要去 "ns" 这个命名空间里找 Foo。

撰写回答