Windows下为Python编译C扩展模块

工具:CodeBlocks 13.12

 

步骤


 

1 打开CodeBlocks新建工程:Shared library   --   c    --  sample    [默认GUN GCC Complier就行]

  右键sample目录,Build options添加以下三项内容:

  Linker settings  -- add  --  C:\Python34\libs\python34.lib     [库文件]

  Search directories  --  Linker  --  C:\Python34\libs

  Search directories  --  Compiler  --  C:\Python34\include      ['Python.h'等头文件]


 

2 编辑main.c文件

#include <stdio.h>
#include <Python.h>

int c_add(int x, int y)     // 正常的C格式
{
    return x+y;
}

static PyObject *add(PyObject *self, PyObject *args)   // 以下都是Python.h中的类型、方法
{
    int a, b;
    if(!PyArg_ParseTuple(args,"ii", &a, &b))
    {
        return NULL;
    }
    return (PyObject*)Py_BuildValue("i", c_add(a,b));
}

/*模块方法表*/
static PyMethodDef AddMethods[] = { {"plus", add, METH_VARARGS, "add a and b"}, //add方法在模块中的名字 { NULL, NULL, 0, NULL} };
/*模块结构*/
static struct PyModuleDef addmodule = { PyModuleDef_HEAD_INIT, "sample", //模块名 "A add module", //文档字符串 -1, //返回状态 AddMethods       // 上面的方法表 }; PyMODINIT_FUNC PyInit_add(void) { return PyModule_Create(&addmodule); }

3 编译

在/bin/Debuge/目录下的libsample.dll就是我们所需要的文件,

重命名sample.pyd,放到import可以找到的地方,就可以在python中import sample了(一般放在C:\Python34\DLLs\中)

 

更具体的看CookBook官方文档

 

转载于:https://www.cnblogs.com/roronoa-sqd/p/5446304.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值