
Python C API接口函数
发布日期:2021-05-06 22:02:05
浏览次数:13
分类:技术文章
本文共 4751 字,大约阅读时间需要 15 分钟。
//============================================================================// Name : MyTest.cpp// Author : Arts// Version :// Copyright : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================#include#include "Python.h"#include "stdlib.h"using namespace std;void very_high_layer() { wchar_t *program = Py_DecodeLocale("MyProgram", NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode MyProgram\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;}int run_func() { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pValue; int i; Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\"/root/PycharmProjects/untitled\")"); pName = PyUnicode_DecodeFSDefault("hello"); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, "my_add"); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(2); const char* argv[] = { "4", "5" }; for (i = 0; i < 2; ++i) { pValue = PyLong_FromLong(atoi(argv[i])); 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", "my_add"); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", "hello"); return 1; } if (Py_FinalizeEx() < 0) { return 120; } return 0;}int Run_Utilities(int num, ...) { PyObject *pValue, *presult, *pmodule, *pret; Py_Initialize(); PyRun_SimpleString("import threading"); wchar_t* pstr; const char* mystring = "奔跑吧兄弟!"; size_t mystrlen = sizeof(mystring); size_t* pmystrlen = &mystrlen; // 1 byte char --> 4 bytes wchar_t pstr = Py_DecodeLocale(mystring, pmystrlen); printf("Py_DecodeLocale: %ls\n", pstr); char* myencodestr; size_t errpos = sizeof(int); size_t* perrpos = &errpos; // 4 bytes wchar_t --> 1 byte char myencodestr = Py_EncodeLocale(pstr, perrpos); printf("Py_EncodeLocale: %s\n", myencodestr); // get objects in sys. in this example, get sys.path pValue = PySys_GetObject("path"); cout << "PySys_GetObject: "; PyObject_Print(pValue, stdout, 0); cout << endl; // Import Module PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\"/root/PycharmProjects/untitled\")"); pmodule = PyImport_ImportModule("hello"); cout << "PyImport_ImportModule: "; PyObject_Print(pmodule, stdout, 0); cout << endl; Py_DECREF(pmodule); // get dict in sys.modules presult = PyImport_GetModuleDict(); cout << "PyImport_GetModuleDict: "; PyObject_Print(presult, stdout, 0); cout << endl; // build value pValue = Py_BuildValue("i", 123); cout << "Py_BuildValue: "; PyObject_Print(pValue, stdout, 0); cout << endl; // parse value int ivalue; PyArg_Parse(pValue, "i", &ivalue); cout << "PyArg_Parse: " << ivalue << endl; Py_XDECREF(pValue); // build serveral values va_list va; va_start(va, num); pValue = Py_VaBuildValue("(i, i, i)", va); cout << "Py_VaBuildValue: "; PyObject_Print(pValue, stdout, 0); cout << endl; // parse tuple int i = 0, j = 0, k = 0; PyArg_ParseTuple(pValue, "iii", &i, &j, &k); cout << "i:" << i << endl << "j:" << j << endl << "k:" << k << endl; va_end(va); Py_XDECREF(pValue); // 获取当前所在函数的内建量 presult = PyEval_GetBuiltins(); cout << "PyEval_GetBuiltins: "; PyObject_Print(presult, stdout, 0); cout << endl; // codec: encode and decode pValue = Py_BuildValue("s", "Hello World!"); presult = PyCodec_Encode(pValue, "utf-16-le", "strict"); PyObject_Print(presult, stdout, 0); cout << endl; pret = PyCodec_Decode(presult, "utf-16-le", "strict"); PyObject_Print(pret, stdout, 0); cout << endl; if (Py_FinalizeEx() < 0) { return 120; } return 0;}int main(int argc, char *argv[]) { int ret = 0;#if 0 // 直接在C编译器中运行python语句 very_high_layer();#elif 0 // 执行.py脚本中的函数 ret = run_func();#elif 1 // 测试常用函数 ret = Run_Utilities(3, 111, 222, 333);#endif return ret;}
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2025年03月28日 00时40分04秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
2020年茶艺师(高级)考试内容及茶艺师(高级)考试申请表
2019-03-03
2021年重氮化工艺考试题库及重氮化工艺考试报名
2019-03-03
2021年车工(高级)考试总结及车工(高级)试题及答案
2019-03-03
2021年压力焊证考试及压力焊实操考试视频
2019-03-03
2021年低压电工考试及低压电工考试申请表
2019-03-03
2021年低压电工考试及低压电工考试申请表
2019-03-03
2021年A特种设备相关管理(电梯)考试APP及A特种设备相关管理(电梯)复审考试
2019-03-03
2021年N1叉车司机考试题及N1叉车司机复审模拟考试
2019-03-03
2021年危险化学品经营单位主要负责人考试APP及危险化学品经营单位主要负责人多少钱
2019-03-03
2021年T电梯修理考试技巧及T电梯修理模拟考试软件
2019-03-03
2021年电工(初级)考试及电工(初级)证考试
2019-03-03
大数据学习之Spark——00Spark项目的pom.xml文件
2019-03-03
CodeBlocks开发wxWidgets环境配置详细
2019-03-03
天涯人脉通讯录 - 设计草图
2019-03-03
wxWidgets 最新版2.8.11,终于放出来了
2019-03-03
python学习09:暂停一秒后再输出
2019-03-03
6、ShardingSphere 之 读写分离
2019-03-03
C++ STL
2019-03-03
解方程
2019-03-03