我有一个C ++项目,我想给它一个python-API - 我提供了一个共享库,用户在他的python项目中导入。 C ++代码解析CLI,所以我需要将C ++端(来自python-API)argv作为char **传递,而不是作为列表传递。 有什么建议吗?
答案 0 :(得分:2)
这是使用常规Python / C API(未经测试)编写的函数。请酌情适应boost::python
构造:
char **list_to_argv_array(PyObject *lst)
{
assert (PyList_Check(lst)); // use better error handling here
size_t cnt = PyList_GET_SIZE(lst);
char **ret = new char*[cnt + 1];
for (size_t i = 0; i < cnt; i++) {
PyObject *s = PyList_GET_ITEM(lst, i);
assert (PyString_Check(s)); // likewise
size_t len = PyString_GET_SIZE(s);
char *copy = new char[len + 1];
memcpy(copy, PyString_AS_STRING(s), len + 1);
ret[i] = copy;
}
ret[cnt] = NULL;
return ret;
}
当不再需要数组时,请delete[]
释放所有单个成员以及数组本身。