【发布时间】:2018-08-04 07:56:19
【问题描述】:
今天我正在阅读有关 C++ 中的嵌入式 python 的文章
https://docs.python.org/3/extending/embedding.html
所以,我可以在 C++ 中调用 python 代码。
但在我看来,API 示例中调用 python 的方式并不酷。
我正在考虑以任意方式从 C++ 调用 python 函数,例如:
py_call(script_path,module_name,str1,int2,long3,float4,str5,double6);
或
py_call(script_path,module_name,x,y,z,title);
但我需要使用parameter pack。这是我第一次看到参数包。我一直卡在这里,我不知道如何替换以下代码中的argc 和argv 参数:
template<typename T, typename... Targs>
void py_call(
const string &script,
const string &module,
T value, Targs... Fargs
)
{
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
int i;
pName = PyUnicode_DecodeFSDefault(script.c_str());
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, module.c_str());
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
pValue = PyLong_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else
{
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", module.c_str());
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else
{
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n",script.c_str());
return 1;
}
}
PS。 argc=sizeof...(Fargs)+1 或 argc=sizeof...(Fargs) 取决于功能实现。
【问题讨论】:
-
您的
py_call使用混合类型,而在您的示例中,所有参数都转换为int。argv是您从中提取的部分内容,都是char*。如果您想要一个涵盖所有签名的单一解决方案,您需要将所有类型转换为 PyObjects - 而不仅仅是整数。我可以推荐你看看 SWIG -
@JensMunk 我可以写一个用户定义的类型案例吗?
-
更好的是,您可以使用模板函数重载,这样如果类型是整数,则使用
PyLong_FromLong,如果类型是双精度则使用另一个函数。参见例如stackoverflow.com/questions/2174300/… -
FluentCPP的作者解释的很好,fluentcpp.com/2017/08/15/…
标签: c++ c++11 templates variadic-templates