【问题标题】:Python c++ wrapper : Convert multi-type struct to it's python representation (preferable dictionary)Python c++ 包装器:将多类型结构转换为它的 python 表示形式(首选字典)
【发布时间】:2019-04-20 21:12:06
【问题描述】:

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

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

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

我尝试从相同类型(例如std::vector<float>)创建项目列表,并设法使用Py_BuildValuePyList_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;
    }
}

【问题讨论】:

    标签: python c++ c swig setuptools


    【解决方案1】:

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

    我猜你想按照那个文档用PyDict_SetItemString() 设置值。

    HTH

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-26
      • 2019-03-02
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2011-03-18
      • 2021-06-17
      相关资源
      最近更新 更多