用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进行测试即可
阅读全文
1 0
- 用Python调用C++/C函数
- Python 调用 C函数
- python 调用 c 函数
- Python调用c/c++函数
- Python调用C语言函数
- Python调用C语言函数
- Python调用C语言函数
- Python调用C语言函数
- Python调用C/C++函数
- C调用Python的函数
- Python调用C语言函数
- 001.python调用C函数
- Python调用 c 的函数
- C语言调用Python函数
- C调用Python的函数
- python调用c中函数
- Python调用C/C++函数
- c和python混编,c调用python模块中的函数
- Controller返回值JSON串化失败,HttpMessageNotWritableException异常解决办法
- C++之const关键字
- vuejs cli安装
- mongo的使用
- solr联合多个字段进行检索(multivalued和copyfield的使用)
- 用Python调用C++/C函数
- cookie与session对比(JavaBean)
- Android音量设置流程干货版
- phpcms 用phpexcel导入导出excel
- 配置Log4J
- 【2】施密特(Schimidt)正交化与正交匹配追踪
- CommOperateWriteRedis().delkey(mconn_relate,vid)
- QT使用记录关于调用DLL库文件出现的问题
- FastQC 质控软件的下载及使用方法(一)