2012-08-01 99 views
0

Python正在調用C++函數(使用swig包裝)。如何在python中使用std :: wstring

C++:

std::wstring getFilePathMultiByte(); 

我可以調用這個函數的蟒蛇。問題是我如何使用這個返回的wstring?想要將文件名追加到此路徑中,如下面的輸出中所示,這會產生錯誤。

的Python:

path = getFilePathMultiByte() 
    print path, type(path) 
    file = path + "/Information.log" 

輸出:

_2012ad3900000000_p_std__wstring, type 'SwigPyObject' 
TypeError: unsupported operand type(s) for +: 'SwigPyObject' and 'str' 

如何在Python中創建一個std :: wstring的?這可能會讓我連接。

謝謝。

+0

使用類型(路徑)查看對象的可用方法。另外,'pprint.pprint(path)'會顯示屬性。 – jordanm 2012-08-01 20:15:28

回答

2

下面的例子擔任意在與痛飲2.0我的機器上:

%module test 

%include "std_wstring.i" 

%inline %{ 
    std::wstring foo() { 
    return L"hi"; 
    } 
%} 

然後我用測試:

Python 2.7.3rc2 (default, Apr 22 2012, 22:30:17) 
[GCC 4.6.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import test 
>>> path = test.foo() 
>>> print path, type(path) 
hi <type 'unicode'> 
>>> file = path + "/Information.log" 
>>> print file 
hi/Information.log 
>>> 

我不太確定你做了什麼錯在這裏 - 我的猜測是你沒有得到%include "std_wstring.i",但是很難說出你所看到的東西。

+0

以爲我會得到編譯錯誤,如果適當的包括不存在。我有%包括「stl.i」。讓我試試這個。順便說一句 - 爲你打印(路徑)打印的是什麼? – sambha 2012-08-01 22:25:38

+0

@sambha - 類型爲「」,但我在原始答案中錯誤地標記了它,所以它被當作HTML處理!就SWIG而言,如果它不能充分了解類型以適當地包裝它,它會假設類型是一個不透明的指針,並相應地生成一個包裝。 – Flexo 2012-08-02 06:47:28

+0

謝謝。添加%包括「std_wstring.i」到正確的.i文件解決它。它的Unicode也是我的。我在字符串中有一些中文字符,所以打印由於其他原因而失敗。在下一個。我也必須在我的問題中編輯。 – sambha 2012-08-02 14:49:50

相關問題