Python C++ 包装器 : Convert multi-type struct to it's python representation (preferable dictionary)

标签 python c++ c swig setuptools

我选择了 setuptools从 python 脚本使用我的 C/C++ 代码。 构建此类包装器的阶段之一是将 C/C++ 返回值转换为 python 对象。

到目前为止,我能够转换简单的原始值和原始值列表。但是,我希望将其扩展为多值结构,如下例所示。

我现在的主要挑战是如何创建 python 结构表示 ( PyObject* ret = PyList_New(...); ) 以及如何使用不同的类型正确设置它的值。

我尝试创建相同类型的项目列表(例如 std::vector<float> )并设法使用 Py_BuildValue 正确设置值和 PyList_SetItem ,但我仍在为多种类型而苦苦挣扎......

typedef struct _fileParams 
{
    bool valid;
    int index;
    std::string key;
    std::value value;
} fileParams;

FileDataBase * db;

static PyObject *searchFileInDB(PyObject *self, PyObject *args)
{
    if (db == NULL) 
    {
        PyErr_SetString(PyExc_RuntimeError, "DB could not be initialized");
        return NULL;
    }

    char* fileName = NULL;
    int fileNameSize = 0;
    PyArg_ParseTuple(args, "s#", &fileName, &fileNameSize);
    try 
    {
        fileParams p;
        bool res = db->lookup(fileName, fileNameSize, p);
        PyObject* ret = PyList_New(...);

        if (res) 
        {                    
            PyObject* r1 = Py_BuildValue("b", p.valid);
            PyList_SetItem(ret, 0, r1);

            PyObject* r2 = Py_BuildValue("i", p.index);
            PyList_SetItem(ret, 1, r2);

            PyObject* r1 = Py_BuildValue("s", p.key);
            PyList_SetItem(ret, 2, r3);

            PyObject* r1 = Py_BuildValue("s", p.value);
            PyList_SetItem(ret, 3, r4);
        }
        return ret;
    } catch (...) {
        PyErr_SetString(PyExc_RuntimeError, "failed with C exception");
        return NULL;
    }
}

最佳答案

您可能想查看字典对象:Dictionary Objects

我猜你想根据该文档使用 PyDict_SetItemString() 设置值。

HTH

关于Python C++ 包装器 : Convert multi-type struct to it's python representation (preferable dictionary),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53358886/

相关文章:

python - tflearn to_categorical : Processing data from pandas. df.values:数组数组

python - 如何制作 csv 文件的列表

c++,操作指向数组第一个元素的指针

C错误: lvalue required as left operand of assignment

python - 使用索引遍历 numpy(相当于 python 枚举的 numpy)

python - 如何检查列表是否已排序?

c++ - 如何将常量指针传递给类中的方法

c++ - 如何在 native 插件中创建 node.js 错误对象?

c - 为什么我们需要解决 `make` 和 `make install` 之后的依赖关系?

c - 了解如何在 R 中处理 .Internal C 函数