2010-09-12 347 views
3

我在使用SWIG 1.3.40(以及我也试过1.3.31)时遇到了以下简单示例时遇到问题。只要我不将它包装在名称空间中,Foo结构就会作为一个Python模块来发布,但只要我这样做,我会在生成的test_wrap.c中收到编译错误。SWIG - 命名空间问题

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'和'命名空间'符号。

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’ 
+0

你能张贴生成的文件test_wrap.c的相关部分吗?并且请注意,g ++默认在文件扩展名中查找以确定文件所在的语言,因此test_wrap.c将被编译为C代码,而不是C++。 – 2010-09-13 20:13:37

回答

12

在您的test.i文件中,在#include后面添加一个“using namespace ns”行。没有这个,你的swig包装器代码将不知道在“ns”命名空间中寻找Foo。

+1

什么是命名空间是在C++头中的命名空间内。你如何在界面文件中处理它。例如'namespace school {namespace college {.... ....}}' – nikk 2017-03-25 01:15:58

+1

@nikk'using namespace school :: college;',可能与'using namespace school;'一起使用' – JETM 2017-03-29 14:49:30