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

方式一:使用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, Extension

mymodule=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.py
import session

session.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.py
import ctypes
lib=ctypes.cdll.LoadLibrary("./libhelloworld.so")
num=lib.add(5,7)
print "num=",num

执行 python testforc.py结果:num=12
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值