我选择了 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;
}
}
最佳答案
关于Python C++ 包装器 : Convert multi-type struct to it's python representation (preferable dictionary),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53358886/