2014-05-16 36 views
1

我的C++代碼有這樣的事情:痛飲:在結構和分配自定義類型在Python

struct Data 
{ 
    CustomType member; 
}; 

我痛飲.i文件有%類型映射(中)和%類型映射(出)到Python字符串轉換爲從CustomType(這是工作的罰款參數和返回值)

在我的蟒蛇,我這樣做:

d = Data() 
d.member = "Hello" 

和Python給了我在運行時出現此錯誤: 類型錯誤:方法「Data_member_set」,鍵入「CustomType *」

我嘗試的論點2以下沒有作用:

%typemap(memberin) CustomType 
{ 
    $target = *$source; 
} 

如何讓蟒蛇讓我分配給會員嗎?

回答

0

如果CustomType可以從一個字符串創建,你應該能夠做到

d.member = CustomType("Hello") 

如果那麼你有沒有通過.i文件導出CustomType,也沒有失敗構造函數需要一個字符串。

+0

因爲CustomType沒有暴露蟒蛇該解決方案並沒有爲我工作 - 在Python我們只使用了Python海峽型。用str(...)替換CustomType(...)不起作用。 – njaard

+0

@njaard那麼你期望能夠分配給它嗎? – Schollii

+0

我期望它從python str轉換,就像我將str作爲參數傳遞給接受CustomType的函數一樣 – njaard

0

你需要寫這樣的事:

%typemap(in) CustomType* (CustomType tmp, int res) 
// or even: %typemap(in) CustomType* ($*1_type tmp, int res) 
{ 
    if (PyString_Check($input)) 
    { 
    tmp = (PyString_AsString($input)); 
    $1 = &tmp; 
    } 
    else 
    { 
    res = SWIG_ConvertPtr($input, (void **) &$1,$1_descriptor, 0 | 0); 
    if (!SWIG_IsOK(res)) { 
     SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " "$argnum"" of type '" "$1_type""'.\n" 
     " Possible argument types are: 'string' and '" "$*1_type" "'\n"); 
    } 
    } 
} 

這意味着:

  1. 的Python不允許您覆蓋的assignemet操作。相反,SWIG的 會爲您的 C++代碼中的所有可能的賦值生成包裝函數。在「=」可能會注入包裝函數調用的每個地方。
  2. 使用上面的'typemap',您可以從a)CustomType和b)內置的Pyton 字符串初始化CustomType的對象 。
  3. 'typemap'中的代碼只是由SWIG生成的包裝器finction的代碼片段。
  4. 您可以在包裝函數中定義CustomType的局部變量。 第一行圓括號中的代碼是局部的 變量,範圍是整個函數。

我建議你打開* _pywrap.cxx文件(其中一個是由SWIG生成的),並根據你的'typemap'檢查它實際生成的內容。

有關詳細信息,與官方公報文檔諮詢:http://www.swig.org/Doc1.3/SWIGDocumentation.html