程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C/C++與Python互相調用

C/C++與Python互相調用

編輯:C++入門知識

1、例程:

test.c


[cpp]
#include "Python.h"  
 
 
void HelloWorld(){ 
     Py_Initialize(); 
        PyRun_SimpleString("import sys");  
        PyRun_SimpleString("print 'hi,python!'"); 
        PyRun_SimpleString("sys.path.append('./')"); 
 
 
     PyObject * pModule = NULL; 
     PyObject * pFunc = NULL; 
     printf("11111 %x\n",pModule); 
     pModule =PyImport_ImportModule("mypy"); 
        printf("11111 %x\n",pModule); 
     pFunc= PyObject_GetAttrString(pModule, "HelloWorld"); 
     PyEval_CallObject(pFunc, NULL); 
     Py_Finalize(); 

 
 
void main(){ 
        printf("tttttt\n"); 
        HelloWorld(); 

#include "Python.h"


void HelloWorld(){
     Py_Initialize();
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("print 'hi,python!'");
        PyRun_SimpleString("sys.path.append('./')");


     PyObject * pModule = NULL;
     PyObject * pFunc = NULL;
     printf("11111 %x\n",pModule);
     pModule =PyImport_ImportModule("mypy");
        printf("11111 %x\n",pModule);
     pFunc= PyObject_GetAttrString(pModule, "HelloWorld");
     PyEval_CallObject(pFunc, NULL);
     Py_Finalize();
}


void main(){
        printf("tttttt\n");
        HelloWorld();
}
mypy.py


[python]
#!/usr/bin/env python  
print '2222' 
def HelloWorld(): 
  print 'this is Helloworld' 

#!/usr/bin/env python
print '2222'
def HelloWorld():
  print 'this is Helloworld'
編譯: mips-linux-gnu-gcc -EL test.c -L./lib -lpython2.7 -I./include/python2.7/


2、例程:

test.cpp


[cpp]
#include <iostream>    
#include "Python.h"  
    
using namespace std;   
    
void HelloWorld();   
void Add();   
void TestTransferDict();   
void TestClass();   
    
int main()   
{   
     cout << "Starting Test..." << endl;   
    
     cout << "HelloWorld()-------------" << endl;   
     HelloWorld();   
     cout << "Add()--------------------" << endl;   
     Add();   
     cout << "TestDict-----------------" << endl;   
     TestTransferDict();   
     cout << "TestClass----------------" << endl;   
     TestClass();   
    
//     system("pause");    
     return 0;   
}   
    
void HelloWorld()   
{   
     Py_Initialize(); 
        PyRun_SimpleString("import sys");  
        PyRun_SimpleString("print 'hi,python!'"); 
        PyRun_SimpleString("sys.path.append('./')"); 
     PyObject * pModule = NULL; 
     PyObject * pFunc = NULL; 
     pModule =PyImport_ImportModule("Test001"); 
     pFunc= PyObject_GetAttrString(pModule, "HelloWorld"); 
     PyEval_CallObject(pFunc, NULL); 
     Py_Finalize(); 
}   
    
  
void Add()   
{   
     Py_Initialize();   
        PyRun_SimpleString("import sys");  
        PyRun_SimpleString("sys.path.append('./')");    
     PyObject * pModule = NULL;       
     PyObject * pFunc = NULL;         
     pModule =PyImport_ImportModule("Test001"); 
     pFunc= PyObject_GetAttrString(pModule,"add"); 
     PyObject *pArgs = PyTuple_New(2); 
     PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 5)); 
     PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 7)); 
     PyObject *pReturn = NULL;   
     pReturn = PyEval_CallObject(pFunc, pArgs); 
     int result;   
     PyArg_Parse(pReturn, "i", &result); 
     cout << "5+7 = " << result << endl;   
    
     Py_Finalize();                   
}   
    
void TestTransferDict()   
{   
     Py_Initialize();   
        PyRun_SimpleString("import sys"); 
        PyRun_SimpleString("sys.path.append('./')"); 
     PyObject * pModule = NULL;       
     PyObject * pFunc = NULL;         
     pModule =PyImport_ImportModule("Test001"); 
     pFunc= PyObject_GetAttrString(pModule, "TestDict"); 
     PyObject *pArgs = PyTuple_New(1);    
     PyObject *pDict = PyDict_New(); 
     PyDict_SetItemString(pDict, "Name", Py_BuildValue("s", "WangYao")); 
     PyDict_SetItemString(pDict, "Age", Py_BuildValue("i", 25)); 
     PyTuple_SetItem(pArgs, 0, pDict); 
     PyObject *pReturn = NULL;   
     pReturn = PyEval_CallObject(pFunc, pArgs); 
     int size = PyDict_Size(pReturn);   
     cout <<"TTTTTTTT" << size << endl;   
     PyObject *pNewAge = PyDict_GetItemString(pReturn, "Age");   
     int newAge;   
     PyArg_Parse(pNewAge, "i", &newAge);   
     cout << "True Age: " << newAge << endl;   
        
     Py_Finalize();                   
}   
    
void TestClass()   
{   
     Py_Initialize();   
        PyRun_SimpleString("import sys"); 
        PyRun_SimpleString("sys.path.append('./')"); 
     PyObject * pModule = NULL;       
     PyObject * pFunc = NULL;         
     pModule =PyImport_ImportModule("Test001"); 
     pFunc= PyObject_GetAttrString(pModule, "TestDict");  
     PyObject *pClassPerson = PyObject_GetAttrString(pModule, "Person");   
     PyObject *pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);   
     PyObject_CallMethod(pInstancePerson, "greet", "s", "Hello Kitty"); 
    
     Py_Finalize();             

#include <iostream> 
#include "Python.h"
  
using namespace std; 
  
void HelloWorld(); 
void Add(); 
void TestTransferDict(); 
void TestClass(); 
  
int main() 

     cout << "Starting Test..." << endl; 
  
     cout << "HelloWorld()-------------" << endl; 
     HelloWorld(); 
     cout << "Add()--------------------" << endl; 
     Add(); 
     cout << "TestDict-----------------" << endl; 
     TestTransferDict(); 
     cout << "TestClass----------------" << endl; 
     TestClass(); 
  
//     system("pause"); 
     return 0; 

  
void HelloWorld() 

     Py_Initialize();
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("print 'hi,python!'");
        PyRun_SimpleString("sys.path.append('./')");
     PyObject * pModule = NULL;
     PyObject * pFunc = NULL;
     pModule =PyImport_ImportModule("Test001");
     pFunc= PyObject_GetAttrString(pModule, "HelloWorld");
     PyEval_CallObject(pFunc, NULL);
     Py_Finalize();

  
 
void Add() 

     Py_Initialize(); 
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");  
     PyObject * pModule = NULL;     
     PyObject * pFunc = NULL;       
     pModule =PyImport_ImportModule("Test001");
     pFunc= PyObject_GetAttrString(pModule,"add");
     PyObject *pArgs = PyTuple_New(2);
     PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 5));
     PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 7));
     PyObject *pReturn = NULL; 
     pReturn = PyEval_CallObject(pFunc, pArgs);
     int result; 
     PyArg_Parse(pReturn, "i", &result);
     cout << "5+7 = " << result << endl; 
  
     Py_Finalize();                 

  
void TestTransferDict() 

     Py_Initialize(); 
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");
     PyObject * pModule = NULL;     
     PyObject * pFunc = NULL;       
     pModule =PyImport_ImportModule("Test001");
     pFunc= PyObject_GetAttrString(pModule, "TestDict");
     PyObject *pArgs = PyTuple_New(1);  
     PyObject *pDict = PyDict_New();
     PyDict_SetItemString(pDict, "Name", Py_BuildValue("s", "WangYao"));
     PyDict_SetItemString(pDict, "Age", Py_BuildValue("i", 25));
     PyTuple_SetItem(pArgs, 0, pDict);
     PyObject *pReturn = NULL; 
     pReturn = PyEval_CallObject(pFunc, pArgs);
     int size = PyDict_Size(pReturn); 
     cout <<"TTTTTTTT" << size << endl; 
     PyObject *pNewAge = PyDict_GetItemString(pReturn, "Age"); 
     int newAge; 
     PyArg_Parse(pNewAge, "i", &newAge); 
     cout << "True Age: " << newAge << endl; 
      
     Py_Finalize();                 

  
void TestClass() 

     Py_Initialize(); 
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");
     PyObject * pModule = NULL;     
     PyObject * pFunc = NULL;       
     pModule =PyImport_ImportModule("Test001");
     pFunc= PyObject_GetAttrString(pModule, "TestDict");
     PyObject *pClassPerson = PyObject_GetAttrString(pModule, "Person"); 
     PyObject *pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL); 
     PyObject_CallMethod(pInstancePerson, "greet", "s", "Hello Kitty");
  
     Py_Finalize();           
}
Test001.py


[python]
def HelloWorld():   
    print "Hello World"   
def add(a, b):   
    return a+b   
def TestDict(dict):   
    print dict   
    dict["Age"] = 17   
    return dict   
class Person:   
    def greet(self, greetStr):   
        print greetStr   
#print add(5,7)    
#a = raw_input("Enter To Continue...") 

def HelloWorld(): 
    print "Hello World" 
def add(a, b): 
    return a+b 
def TestDict(dict): 
    print dict 
    dict["Age"] = 17 
    return dict 
class Person: 
    def greet(self, greetStr): 
        print greetStr 
#print add(5,7) 
#a = raw_input("Enter To Continue...")
3、

其中


[cpp]
PyRun_SimpleString("import sys"); 
PyRun_SimpleString("sys.path.append('./')"); 

        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");

分別導入sys,接著設置py文件的路徑

 


4、PySys_SetArgv、PySys_SetPath和PyRun_AnyFile的用法:

test1.c


[cpp]
#include "Python.h"  
 
void HelloWorld(){ 
        char *argv[2]; 
        unsigned int argc; 
        argc = 2; 
        char *tmp="hello"; 
        char *tmp1="world"; 
 
        argv[0]= tmp; 
        argv[1]= tmp1; 
        Py_Initialize(); 
        PySys_SetArgv(argc, argv); 
        PySys_SetPath("./"); 
//      PyRun_SimpleString("import sys");   
//      PyRun_SimpleString("sys.path.append('./')");  
        PyRun_SimpleString("print 'hi,python!'"); 
 
        PyObject * pModule = NULL; 
        PyObject * pFunc = NULL; 
        pModule =PyImport_ImportModule("mypy"); 
        Py_Finalize(); 

 
void main(){ 
        printf("tttttt\n"); 
        HelloWorld(); 

#include "Python.h"

void HelloWorld(){
        char *argv[2];
        unsigned int argc;
        argc = 2;
        char *tmp="hello";
        char *tmp1="world";

        argv[0]= tmp;
        argv[1]= tmp1;
        Py_Initialize();
        PySys_SetArgv(argc, argv);
        PySys_SetPath("./");
//      PyRun_SimpleString("import sys");
//      PyRun_SimpleString("sys.path.append('./')");
        PyRun_SimpleString("print 'hi,python!'");

        PyObject * pModule = NULL;
        PyObject * pFunc = NULL;
        pModule =PyImport_ImportModule("mypy");
        Py_Finalize();
}

void main(){
        printf("tttttt\n");
        HelloWorld();
}
mypy.py


[python]
#!/usr/bin/env python  
import sys 
print '----sys.argv[0]: ',sys.argv[0] 
print '----sys.argv[1]: ',sys.argv[1] 
print '2222' 
def HelloWorld(): 
  print 'this is Helloworld' 
if __name__ == '__main__': 
  print 'this is main 

#!/usr/bin/env python
import sys
print '----sys.argv[0]: ',sys.argv[0]
print '----sys.argv[1]: ',sys.argv[1]
print '2222'
def HelloWorld():
  print 'this is Helloworld'
if __name__ == '__main__':
  print 'this is main
PySys_SetArgv,設置參數;


PySys_SetPath,設置py文件路徑;


如果用下面的代碼:


[cpp]
PyObject* file = PyFile_FromString((char *) "mypy.py", (char*)"r"); 
FILE *fp = PyFile_AsFile(file); 
PyRun_AnyFile(fp,"mypy.py"); 

      PyObject* file = PyFile_FromString((char *) "mypy.py", (char*)"r");
      FILE *fp = PyFile_AsFile(file);
      PyRun_AnyFile(fp,"mypy.py");
來代替:


[cpp]
PyObject * pModule = NULL; 
pModule =PyImport_ImportModule("mypy"); 

        PyObject * pModule = NULL;
        pModule =PyImport_ImportModule("mypy");
也可以執行mypy.py,但是PyRun_AnyFile會執行mypy.py中的__main__中的代碼;

 

 


二、【Python調用C/C++】

 Python開發效率高,運行效率低。而c/c++恰恰相反。因此在python腳本中調用c/c++的庫,對python進行擴展,是很有必要的。使用python api,http://www.python.org/doc/


1、

 

test.c


[cpp]
#include <stdio.h>  
void display() { 
    printf("This is Display Function\n");  

#include <stdio.h>
void display() {
 printf("This is Display Function\n");
}
gcc -shared -fpic test.c -o libtestso1.so -I./include/python2.7


test.py


[python]
import ctypes 
so = ctypes.CDLL("./libtestso1.so") 
so.display() 

import ctypes
so = ctypes.CDLL("./libtestso1.so")
so.display()

2、

testso2.cpp

 

[cpp]
#include<iostream>  
class TestLib{ 
        public: 
                void display(); 
                void display(int a); 
 
 
}; 
void TestLib::display() { 
       std::cout<<"First display"<<std::endl; 

 
 
void TestLib::display(int a) { 
        std::cout<<"Second display"<<std::endl; 

extern "C" { 
        TestLib obj; 
        void display() { 
               obj.display();  
        } 
        void display_int() { 
               obj.display(2);  
        } 

#include<iostream>
class TestLib{
        public:
                void display();
                void display(int a);


};
void TestLib::display() {
       std::cout<<"First display"<<std::endl;
}


void TestLib::display(int a) {
        std::cout<<"Second display"<<std::endl;
}
extern "C" {
        TestLib obj;
        void display() {
               obj.display();
        }
        void display_int() {
               obj.display(2);
        }
}
g++ -shared -fpic testso2.cpp -o libtestso2.so -I./include/python2.7/


testso2.py

 

[python]
import ctypes 
so = ctypes.CDLL("./libtestso2.so") 
so.display() 
so.display_int(1) 

import ctypes
so = ctypes.CDLL("./libtestso2.so")
so.display()
so.display_int(1)

 

3、

 


testso.cpp


[cpp]
#include <python2.6/Python.h> //包含python的頭文件    
// 1 c/cpp中的函數    
int my_c_function(const char *arg) {   
  int n = system(arg);   
  return n;   
}   
// 2 python 包裝    
static PyObject * wrap_my_c_fun(PyObject *self, PyObject *args) {   
  const char * command;   
  int n;   
  if (!PyArg_ParseTuple(args, "s", &command))//這句是把python的變量args轉換成c的變量command    
    return NULL;   
  n = my_c_function(command);//調用c的函數    
  return Py_BuildValue("i", n);//把c的返回值n轉換成python的對象    
}   
// 3 方法列表    
static PyMethodDef MyCppMethods[] = {   
    //MyCppFun1是python中注冊的函數名,wrap_my_c_fun是函數指針    
    { "MyCppFun1", wrap_my_c_fun, METH_VARARGS, "Execute a shell command." },   
    { NULL, NULL, 0, NULL }   
};   
// 4 模塊初始化方法    
PyMODINIT_FUNC initMyCppModule(void) {   
  //初始模塊,把MyCppMethods初始到MyCppModule中    
  PyObject *m = Py_InitModule("MyCppModule", MyCppMethods);   
  if (m == NULL)   
    return;   
}   

#include <python2.6/Python.h> //包含python的頭文件 
// 1 c/cpp中的函數 
int my_c_function(const char *arg) { 
  int n = system(arg); 
  return n; 

// 2 python 包裝 
static PyObject * wrap_my_c_fun(PyObject *self, PyObject *args) { 
  const char * command; 
  int n; 
  if (!PyArg_ParseTuple(args, "s", &command))//這句是把python的變量args轉換成c的變量command 
    return NULL; 
  n = my_c_function(command);//調用c的函數 
  return Py_BuildValue("i", n);//把c的返回值n轉換成python的對象 

// 3 方法列表 
static PyMethodDef MyCppMethods[] = { 
    //MyCppFun1是python中注冊的函數名,wrap_my_c_fun是函數指針 
    { "MyCppFun1", wrap_my_c_fun, METH_VARARGS, "Execute a shell command." }, 
    { NULL, NULL, 0, NULL } 
}; 
// 4 模塊初始化方法 
PyMODINIT_FUNC initMyCppModule(void) { 
  //初始模塊,把MyCppMethods初始到MyCppModule中 
  PyObject *m = Py_InitModule("MyCppModule", MyCppMethods); 
  if (m == NULL) 
    return; 

 

mips-linux-gnu-g++ -EL -shared -fpic testso.cpp -o MyCppModule.so -L./lib -lpython2.7 -I./include/python2.7/


testso.py

 

[python]
# -*- coding: utf-8 -*-    
import MyCppModule   
#導入python的模塊(也就是c的模塊,注意so文件名是MyCppModule      
r = MyCppModule.MyCppFun1("ls -l")   
print r    
print "OK"  

# -*- coding: utf-8 -*- 
import MyCppModule 
#導入python的模塊(也就是c的模塊,注意so文件名是MyCppModule   
r = MyCppModule.MyCppFun1("ls -l") 
print r  
print "OK" PS:PyModule_Create和Py_InitModule的區別:http://stackoverflow.com/questions/10509400/difference-between-pymodinit-func-and-pymodule-create

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved