解決方案。
步驟1:向Module類添加一個成員,並添加兩個方法。
class Module {
public:
PyObject *obj;
void incref() { Py_INCREF(obj); }
void decref() { Py_DECREF(obj); }
...
};
步驟2:增加在register_module引用計數()。
void register_module(Module *m) {
m->incref();
...
}
(不要忘記某處降低它)
步驟3:入侵的SWIG生成的包裝,在模塊對象從Python的構造成與obj成員設置爲的PyObject包裝。
在痛飲生成的文件ModulePYTHON_wrap.cxx,找到:
SWIGINTERN PyObject *_wrap_new_Module(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
...
Module *result = 0 ;
...
if (arg1 != Py_None) {
/* subclassed */
result = (Module *)new SwigDirector_Module(arg1);
} else {
result = (Module *)new Module();
}
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Module, SWIG_POINTER_NEW | 0);
return resultobj;
...
}
插入result->obj =
前resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Module, SWIG_POINTER_NEW | 0);
我們得到:
result->obj = resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Module, SWIG_POINTER_NEW | 0);
步驟4:指示SWIG自動實現修復在生成的包裝器中。
在接口文件中添加以下typemap聲明。
%typemap(out) Module* {
result->obj = $result = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Module, SWIG_POINTER_NEW | 0);
}
這有效地覆蓋了默認情況下生成的用於包裝新Module對象的代碼。
如果班級有導演,則應該在導演python對象上。然後,typemap代碼將變爲:$ result = SWIG_NewPointerObj(SWIG_as_voidptr(result),SWIGTYPE_p_Module,SWIG_POINTER_NEW | 0); Swig :: Director * dr = dynamic_cast(result); result-> obj = dr? dr-> swig_get_self():$ result; –
user2179288
2013-03-28 19:46:35