C/C++是可以寫 python 庫的,這里咧也可以寫出 python 庫,讓 python 調(diào)用,來擴展 python。
到目前為止,嵌入式Python解釋器還不能從應用程序本身訪問功能。Python API通過擴展嵌入式解釋器來實現(xiàn)這一點。也就是說,嵌入式解釋器通過應用程序提供的例程得到擴展。雖然聽起來很復雜,但也沒那么糟糕。只需暫時忘記應用程序啟動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. 最后是運行結(jié)果
輸入了 4 個參數(shù),所以總共參數(shù)是 5 個。
更多文章、技術(shù)交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

