Python c++ 包装器:将多类型结构转换为它的 python 表示(首选字典)
Python c++ wrapper : Convert multi-type struct to it's python representation (preferable dictionary)
我选择 setuptools
使用来自 python 脚本的 C/C++ 代码。
构建此类包装器的其中一个阶段是将 C/C++ return 值转换为 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
我选择 setuptools
使用来自 python 脚本的 C/C++ 代码。
构建此类包装器的其中一个阶段是将 C/C++ return 值转换为 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