c++ - SWIG C++ 到 Python:将 std::list 作为参数返回给 Python

标签 c++ python swig

我正在尝试从 Python 调用 C++ 中的方法,该方法返回一个 std::list 作为参数。

这是 C++ 原型(prototype):

void FindAllServices(int id, std::list<Service*> &services)

这是我的 std::list 类型映射:

%typemap(in) (std::list<Service*> &) (std::list<Service*> temp) {
  $1 = &temp;
}

%typemap(argout) (std::list<Service*>&) {
    Py_XDECREF($result);   /* Blow away any previous result */
    $result = PyList_New((*$1).size());
    qList<Service*>::iterator it = (*$1).begin();
    int i = 0;
    while(it != (*$1).end()) {
        PyList_SetItem($result,i,SWIG_NewPointerObj((void*)(*it), SWIGTYPE_p_Service, 0));
        it++; i++;
    }
}

当我从 Python 调用该函数时,我可以中断 C++ 代码并看到一切正常(即一些服务指针已复制到列表中)。然而,我在 Python 中得到的列表是空的。

你知道我可能做错了什么吗?

谢谢!

最佳答案

您的 argout 代码会创建一个新列表。您必须获得对原始列表的引用并修改它。我不懂 swig,所以我不知道该怎么做。

对于 python 接口(interface),我通常会包装它以便返回一个新列表而不是修改传入的列表。这是一个 C++ 习语,但不是真正的 Python 习语。

关于c++ - SWIG C++ 到 Python:将 std::list 作为参数返回给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8842229/

相关文章:

<< 运算符的 c++11 特定重载

python - 尝试在 python 中创建一个坐标圆

python - 在 SWIG 中为包含 union 的结构创建类型映射 (Python)

python - 安装pocketsphinx python模块: command 'swig.exe' failed

c++ - 一个定义规则 - 内联函数的多个定义

c++ - gstreamer 将元素添加到通过 gst_parse_launch 创建的管道中

python - Django 如何按相关模型过滤和排序查询集

android-ndk - 是否可以使用带有 cgo 和/或 SWIG 或类似工具的 NDK 在 Go 中构建 Android 游戏?

c++ - 多线程程序中的 std::atomic<int> memory_order_relaxed VS volatile sig_atomic_t

具有格式化程序的 Python 日志记录模块导致 AttributeError