2017-03-17 119 views
1

我試圖SWIG渦卷(版本3)INT的C++ STL地圖一類的指針,到Python 3:SWIG類型映射爲指針的STL地圖一類

example.h文件

#include <map> 

using namespace std; 

class Test{}; 

class Example{ 
public: 
    map<int,Test*> my_map; 
    Example() 
    { 
     int a=0; 
     Test *b = new Test(); 
     this->my_map[a] = b; 
    } 
}; 

example.i

%module example 

%{ 
    #include "example.h" 
%} 

using namespace std; 

%typemap(out) map<int,Test*> { 
    $result = PyDict_New(); 

    map<int,Test*>::iterator iter; 
    Test* theVal; 
    int theKey; 

    for (iter = $1.begin(); iter != $1.end(); ++iter) { 
    theKey = iter->first; 
    theVal = iter->second; 
    PyObject *value = SWIG_NewPointerObj(SWIG_as_voidptr(theVal), SWIGTYPE_p_Test, 0); 
    PyDict_SetItem($result, PyInt_FromLong(theKey), value); 
    } 
}; 

class Test{}; 

class Example{ 
public: 
    map<int,Test*> my_map; 
}; 

沒有錯誤,但是現在在Python 3,運行

import example 
t = example.Example() 
t.my_map 

回報

<Swig Object of type 'map< int,Test * > *' at 0x10135e7b0> 

,而不是一本字典。它也有一個指向地圖的指針,而不是地圖。如何編寫正確的%typemap將STL映射轉換爲Python 3字典?

我已經能夠做到這一點的地圖例如。 int int - 它是指向給我麻煩的類的指針。

謝謝。

回答

1

讓我得到你的SWIG手冊中的相關條目... here

這告訴你的是,成員變量my_map通過該SWIG生成一個getter,它返回一個map<int,Test*> *(或參考訪問,如果你給%naturalvar指令)。因此,必須編寫您的輸出類型映射來處理map<int,Test*> *而不是map<int,Test*>

+0

謝謝!我想這是明顯的答案。爲什麼getter會返回一個指針,而不是對象?例如,如果我們改爲SWIG封裝一個返回地圖'map my_function();'的函數,那麼SWIG將根據需要返回一個'map '而不是'map *'。 – Kurt

+1

getter返回一個指向成員對象的指針,以避免必須進行復制。如果它通過值返回,則會創建並返回成員對象的副本。這也在SWIG手冊的上面鏈接中討論過。 – m7thon

+0

是有道理的 - 謝謝! – Kurt