用python调用C/C++的两种方式

来源:互联网 发布:手机电脑屏幕同步软件 编辑:程序博客网 时间:2024/05/17 22:14

方式一:使用python库带有的distutils.core

例如下:mysetup.c

#include <Python.h>static PyObject *say_hello(PyObject*self){    printf("hello world!\n");    Py_RETURN_NONE;}static PyObject *calc_pv(PyObject *self,PyObject *args){    int i_ct=0;    int j_ct=0;    if(!PyArg_ParseTuple(args,"i|i",&i_ct,&j_ct))        return NULL;    return Py_BuildValue("i",(i_ct+j_ct));}static PyMethodDef addMethods[]={    {"sayhello",(PyCFunction)say_hello,METH_NOARGS,"say hello!"},    {"sum",(PyCFunction)calc_pv,METH_VARARGS,"calc pv"},    {NULL,NULL,0,NULL}};PyMODINIT_FUNC initsession(void){    PyObject *module;    module=Py_InitModule("session",addMethods);    if(!module)        return;}

上面是我们的c代码,紧接着是我们的python安装,setup.py内容如下:

from distutils.core import setup, Extensionmymodule=Extension('session',sources=['mysetup.c'],language='c')setup(name             = 'mysetuptest',      version          = '1.0',      description      = 'This is a myfirst program test for setup',      ext_modules      = [mymodule])

将这两个文件放在同一个目录下,执行如下命令:
编译 :python setup.py build //执行该命令之后在当前目录底下生成build目录里面有生成的.so库
安装:python setup.py install //执行之后会将build目录底下的so库拷贝到python
//的安装目录一般为/usr/locall/lib/python2.7/dist-packages/目录底下
这样我们的python调用的c代码库就安装好了,下面是一个调用的例子:

mytest.pyimport sessionsession.sayhello()session.sum(5,7)

方式二:使用python的ctypes

例如:helloworld.c

#include <stdio.h>int add(int a,int b){    return a+b;}编译.so库:gcc -shared -fPIC  helloworld.c -o libhelloworld.so

使用:

python脚本:testforc.pyimport ctypeslib=ctypes.cdll.LoadLibrary("./libhelloworld.so")num=lib.add(5,7)print "num=",num执行 python testforc.py结果:num=12
0 0
原创粉丝点击