2010-09-12 349 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