实现这个过程是根据QT中 使用c++调用python这个博客来的,只是我没有作者那么容易就实现了,所以记录下着爬坑经过。
Python官网的文件中有讲解Python嵌入的,这是python3.8的嵌入
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int
main(int argc, char *argv[])
{
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0) {
exit(120);
}
PyMem_RawFree(program);
return 0;
}
运行报错:关于slots
此处参考了Qt与Python混合编程经验记录,感谢大佬的博客!
报错原因:这是由于QT中定义了slots作为关键了,而Python3中有使用slot作为变量,所以有冲突。
解决办法:把Python代码暂时取消冲突的宏定义,然后重新定义相关宏
报错的是object.h:
修改为:
typedef struct{
const char* name;
int basicsize;
int itemsize;
unsigned int flags;
#undef slots //这里取消slots宏定义
PyType_Slot *slots; /* terminated by slot==0. */
#define slots Q_SLOTS //这里恢复slots宏定义与QT中QObjectDefs.h中一致
} PyType_Spec;
运行出现新的报错:
Fatal Python error: failed to get the Python codec of the filesystem encoding