qt与python混合编程,C/C++/Qt与 Python 混合编程(4):扩展嵌入Python
发布日期:2021-06-24 11:32:17 浏览次数:2 分类:技术文章

本文共 1295 字,大约阅读时间需要 4 分钟。

C/C++是可以写 python 库的,这里咧也可以写出 python 库,让 python 调用,来扩展 python。

到目前为止,嵌入式Python解释器还不能从应用程序本身访问功能。Python API通过扩展嵌入式解释器来实现这一点。也就是说,嵌入式解释器通过应用程序提供的例程得到扩展。虽然听起来很复杂,但也没那么糟糕。只需暂时忘记应用程序启动Python解释器。相反,将应用程序看作一组子例程,并编写一些胶水代码,使Python能够访问这些例程,就像编写普通的Python扩展一样。

1. 首先给出代码

1)头文件

#define PY_SSIZE_T_CLEAN

#include

#include

2)定义 API

static int numargs=0;

/* Return the number of arguments of the application command line */

static PyObject*

emb_numargs(PyObject *self, PyObject *args)

{

if(!PyArg_ParseTuple(args, ":numargs"))

return nullptr;

return PyLong_FromLong(numargs);

}

static PyMethodDef EmbMethods[] = {

{"numargs", emb_numargs, METH_VARARGS,

"Return the number of arguments received by the process."},

{nullptr, nullptr, 0, nullptr}

};

static PyModuleDef EmbModule = {

PyModuleDef_HEAD_INIT, "emb", nullptr, -1, EmbMethods,

nullptr, nullptr, nullptr, nullptr

};

static PyObject*

PyInit_emb(void)

{

return PyModule_Create(&EmbModule);

}

这就定义了 emb 库,python 是可以直接 import 的。

3)主程序

nt main(int argc, char *argv[])

{

QCoreApplication a(argc, argv);

numargs = argc;

PyImport_AppendInittab("emb", &PyInit_emb); //初始化 emb 库

Py_Initialize();

PyRun_SimpleString("import emb\n"); //引用 emb 库

PyRun_SimpleString("print('Number of arguments', emb.numargs())\n");

return a.exec();

}

2. 最后是运行结果

输入了 4 个参数,所以总共参数是 5 个。

4f67017f74a23cd17c6d4f1a197ffea4.png

转载地址:https://blog.csdn.net/weixin_32512381/article/details/116213634 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:php strcmp和等于,php strcmp引起的问题
下一篇:amd笔记本安装matlab,AMD matlab的安装(仅供学习)

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月12日 17时42分47秒