C++调用Python
来源:互联网 发布:三线性优化开不开 编辑:程序博客网 时间:2024/06/05 06:09
Background
本意是打算在C++中使用实时制图功能,调用matlab在linux下面的不可取性,选择了python matplotlib作为替换的方法.在Ubuntu 12.04 LTS和eclipse Mars.2 Release (4.5.2)下完成调试.
Steps
- 在Python中,用matplotlib实现显示,并用函数和类进行封装以便进行调用
- C++中实现Python函数和类的调用
- 结合C++ 封装Python调用类和matplotlib进行显示
- 最后将其加入到所需要显示的系统中
Details&Notice
- Python的速度问题.若要完全的将图重画,将会浪费较多的计算机资源,大幅度的降低速度-不到10frames.而仅仅修改图中显示的数据1则可以大大的提高帧率,我的项目中可到80 frames左右.
- 在实际中,C++调用Python使用类的方式显得更加方便高效2.
- 数组的传入3与返回4,不同类型变量的使用,图形显示参数
C++调用Python类
C++ main 函数
#include <Python.h>#include "object.h"int main(int argc, char *argv[]){ PyObject *pName, *pModule, *pDict, *pClass, *pInstance, *pValue; int i, arg[8]; if (argc < 4) { fprintf(stderr,"Usage: call python_filename class_name function_name\n"); return 1; } // Set PYTHONPATH TO working directory setenv("PYTHONPATH", ".", 1); Py_Initialize(); pName = PyString_FromString(argv[1]); pModule = PyImport_Import(pName); pDict = PyModule_GetDict(pModule); // Build the name of a callable class pClass = PyDict_GetItemString(pDict, argv[2]); // Create an instance of the class if (PyCallable_Check(pClass)) { pInstance = PyObject_CallObject(pClass, NULL); } // Build parameter list if( argc > 4 ) { for (i = 0; i < argc - 4; i++) { arg[i] = atoi(argv[i + 4]); }// Call a method of the class with two parameters pValue = PyObject_CallMethod(pInstance, argv[3], "(ii)", arg[0], arg[1]); } else {// Call a method of the class with no parameters pValue = PyObject_CallMethod(pInstance, argv[3], NULL); } if (pValue != NULL) { printf("Return of call : %d\n", PyInt_AsLong(pValue)); Py_DECREF(pValue); } else { PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pName); Py_Finalize(); return 0;}
Python Class
class Multiply: def __init__(self): self.a = 6 self.b = 5 def multiply(self): c = self.a*self.b print 'The result of', self.a, 'x', self.b, ':', c return c def multiply2(self, a, b): c = a*b print 'The result of', a, 'x', b, ':', c return c
以下方式调用程序
call_class py_class Multiply multiplycall_class py_class Multiply multiply2 9 9
欢迎讨论.
0 0
- BCB(C++)调用Python
- C中调用PYTHON
- C调用python
- C调用python
- Python 调用 C函数
- python调用c
- Python 调用C
- c中调用python
- Python调用c/c++
- c 调用python
- python 调用 c 函数
- python调用C函数库
- Python调用C
- Python调用C/C++
- Python调用C程序
- python调用c/c++
- python调用c
- c调用python
- 机器学习中的算法(2)-支持向量机(SVM)基础
- 指针
- 三角形5
- CSS选择器详解一
- IOS学习之[深入浅出Cocoa]iOS网络编程之Socket
- C++调用Python
- http协议详解之url篇
- float x 与 0值作比较的if语句
- 机器学习中的数学(1)-回归(regression)、梯度下降(gradient descent)
- 对于jQuery的click事件出现重复情况的对策
- 关于取模和取余的区别。
- NYOJ-23 取石子(一)
- Error MSB6006: “mt.exe”已退出,代码为 31
- 黑马程序员 —— C语言之关键字