C/C++与 Python 混合编程(4):扩展嵌入Python

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
"); //引用 emb 库
 PyRun_SimpleString("print('Number of arguments', emb.numargs())
");
 return a.exec();
}

2. 最后是运行结果

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

C/C++与 Python 混合编程(4):扩展嵌入Python

展开阅读全文

页面更新:2024-05-24

标签:主程序   这一点   胶水   初始化   嵌入式   应用程序   糟糕   也就是说   例程   定义   参数   代码   功能   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top