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

  1. 在Python中,用matplotlib实现显示,并用函数和类进行封装以便进行调用
  2. C++中实现Python函数和类的调用
  3. 结合C++ 封装Python调用类和matplotlib进行显示
  4. 最后将其加入到所需要显示的系统中

Details&Notice

  1. Python的速度问题.若要完全的将图重画,将会浪费较多的计算机资源,大幅度的降低速度-不到10frames.而仅仅修改图中显示的数据1则可以大大的提高帧率,我的项目中可到80 frames左右.
  2. 在实际中,C++调用Python使用类的方式显得更加方便高效2.
  3. 数组的传入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