用Python调用C++/C函数

来源:互联网 发布:电脑办公软件培训班 编辑:程序博客网 时间:2024/06/06 02:22

运行环境:Ubuntu14.04+Python2.7

第一步:首先创建一个文件夹,并在文件夹中创建一个名为Itcastcpp.c的文件,文件中的代码如下:

#include<stdio.h>#include<stdlib.h>#include<string.h>int fac(int n){  if(n<2)     return 1;  return n*fac(n-1); }char *reverse(char *s){   char t, *p=s, *q=(s+(strlen(s)-1));   while(s&&(p<q)){      t=*p;      *p++=*q;      *q--=t;}      return s;}int test(void)//int main(void) {    char s[1024];    printf("4!==%d\n",fac(4));    printf("8!==%d\n",fac(8));    strcpy(s,"itcastcpp");    printf("reversing 'itcastcpp',we get '%s'\n",reverse(s));    return 0;}

第二步:在liunux中编译运行上面的程序,编译命令如下:

  gcc -o Itcastcpp.c Itcastcpp

 然后运行编译好的文件,命令为

       Itcastcpp

第三步 编写Itcastcpp.h文件,代码如下:

#ifndef ITCASTCPP_H_#define ITCASTCPP_H_int fac(int n);char *reverse(char *s);int test(void);#endif

第四部:编写名字为Itcastcppwrapper.c的包裹函数,代码如下:

#include "Python.h"#include <stdlib.h>#include <string.h>#include "Itcastcpp.h"static PyObject *Itcastcpp_fac(PyObject *self,PyObject *args){int num;if(!PyArg_ParseTuple(args,"i",&num))  return NULL;   return (PyObject *)Py_BuildValue("i",fac(num));}static PyObject *Itcastcpp_doppel(PyObject *self,PyObject *args){char *src;char *mstr;PyObject *retval;if(!PyArg_ParseTuple(args,"s",&src))  return NULL;  mstr=malloc(strlen(src)+1);strcpy(mstr,src);reverse(mstr);retval=(PyObject *)Py_BuildValue("ss",src,mstr);free(mstr);return retval;}static PyObject *Itcastcpp_test(PyObject *self,PyObject *args){test();return (PyObject *)Py_BuildValue("");}static PyMethodDef ItcastcppMethods[]={{"fac",Itcastcpp_fac,METH_VARARGS},{"doppel",Itcastcpp_doppel,METH_VARARGS},{"test",Itcastcpp_test,METH_VARARGS},{NULL,NULL},};void initItcastcpp(void){Py_InitModule("Itcastcpp",ItcastcppMethods);}


第五步:编写setup.py文件,代码如下:

#! /usr/bin/env pythonfrom distutils.core import setup,ExtensionMOD="Itcastcpp"setup(name=MOD,ext_modules=[Extension(MOD,sources=['Itcastcpp.c','Itcastcppwrapper.c'])])

第六步: 执行命令python setup.py build

第七步:进入ipython进行测试即可