首页 > 解决方案 > 用于输入和输出的 Swig Python 类型映射

问题描述

假设我有一个自定义对象MyNamespace::MyProject::MyObj和一个返回其中一个的函数,就像这样......

bool myfunc(int a, MyNamespace::MyProject::MyObj &b);

我发现我可以创建一个类型映射,b通过将它放在我的 .i 文件中,在 Python 的左侧生成一个返回值......

%typemap(in,numinputs=0) ML::Processing::MyObj& {
    // Create a persistent object to hold the result;
    $1 = new ML::Processing::MyObj;
}
%typemap(argout) ML::Processing::MyObj& (PyObject* tmp) {
    // Store the persistent object in a PyObject* that will be destroyed
    // when it goes out of scope.
    tmp = SWIG_NewPointerObj($1, $1_descriptor, SWIG_POINTER_OWN);
    $result = SWIG_Python_AppendOutput($result, tmp);
}

这样,在 Python 中,我可以执行以下操作...

ok,b = mylib.myfunc(1)

到目前为止,一切都很好。但是现在假设我有另一个类似的函数,但MyObj像这样将 a 作为输入......

bool myfunc2(int a, const MyNamespace::MyProject::MyObj &b)

当我尝试在 Python 中调用它时(如下所示)出现Wrong number or type of arguments错误

ok,b = mylib.myfunc(1) # this works correctly
ok = mylib.myfunc2(1,b) # this complains

我认为它与typemap(in,numinputs=0).i 文件有关……就像每次看到 a MyNamespace::MyProject::MyObj &它现在都认为它是返回参数而不是输入。

所以,我的问题是,有没有办法处理这种情况,以便我可以同时拥有输入类型映射和输出类型映射?在此先感谢你们所有的swig-fu大师!

标签: pythonc++swig

解决方案


推荐阅读