C++调用Python模块
来源:互联网 发布:淘宝二手ps4主机能买吗 编辑:程序博客网 时间:2024/05/19 19:32
- 本文主要实现在linux环境下编写cpp文件调用python文件中的模块
代码块
- c++/hello.cpp
#include "Python.h" #include <iostream> using namespace std; int main(){ // 初始化 Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); PyObject * pName = NULL; //声明变量 PyObject * pModule = NULL; PyObject * pFunc = NULL; PyObject * pDict = NULL; pName = PyString_FromString("hello"); pModule = PyImport_Import(pName); //这里是要调用的文件名 if(!pModule){ cout << "加载模块失败" << endl; } pDict = PyModule_GetDict(pModule); if(!pDict){ cout << "加载dict失败" << endl; } pFunc= PyDict_GetItemString(pDict, "hello"); //这里是要调用的函数名 if(!pFunc){ cout << "加载函数失败" << endl; } PyObject * args = PyTuple_New(1); PyTuple_SetItem(args, 0, Py_BuildValue("s","Cattie")); PyObject * pRet = PyEval_CallObject(pFunc, args); //调用函数 if(pRet){ long result = PyInt_AsLong(pRet); cout << "result:" << result; } Py_Finalize(); // 释放资源 }
- python/hello.py
def hello(name): print("hello, %s" %name) return 123
- 命令行
# g++ hello.cpp -I/usr/local/include/python2.7 -ldl -lutil -lpthread -lpython2.7 -o hello
- 结果
阅读全文
0 0
- PYTHON 调用 C/C++模块
- C调用python,如何调用pymongo模块
- python调用C模块的方法
- Python使用bitey调用C模块
- Python与C/C++ 模块相互调用
- Python与C/C++ 模块相互调用
- Python与C/C++ 模块相互调用
- linux 下C调用Python 模块
- Python与C/C++ 模块相互调用
- linux 下Python调用C模块
- linux 下C调用Python 模块
- linux 下Python调用C模块
- linux 下Python调用C模块
- Python调用C模块和性能分析
- linux 下C调用Python 模块
- linux 下C调用Python 模块
- Python 调用C模块以及性能分析
- Linux下用Python调用C模块
- 隐马尔科夫模型(二)
- C++实现WEB功能方法总结
- cookie和session的区别
- 发现了一个好用的WEB项目打印控件--四方打印
- 阿里、百度等多家公司Java面试记录与总结
- C++调用Python模块
- Hadoop MapReduce执行过程中map和reduce执行过程
- 算法题/数组中出现次数超过一半的数字
- Java的反射
- 拨开字符编码的迷雾
- sparkStreaming总结
- web页面跳转
- Ubuntu串口通信
- partial修饰介绍