python的C扩展

前提条件

c编译器用DEV-C++,

python(sys.version):'2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]'

一、新建DEV-C++的DLL工程


二、设置DEV工程属性

参考 C中嵌入python 文中的设置工程属性

三、生成python的C扩展“.pyd”文件

编写DLL的代码,代码如下:

#include <Python.h>

static PyObject *Log( PyObject *self, PyObject *args )
{
    const char *s;
    if ( !PyArg_ParseTuple( args, "s", &s ) )
        return NULL;

    return Py_BuildValue( "ss", "PydMath.Log log:", s );
}

static PyObject *Sub( PyObject *self, PyObject *args )
{
    int a, b;
    if ( !PyArg_ParseTuple( args, "ii", &a, &b ) )
        return NULL;

    return Py_BuildValue( "i", a - b );
}

static PyObject *Add( PyObject *self, PyObject *args )
{
    int a, b, sum;
    if ( !PyArg_ParseTuple( args, "ii", &a, &b ) )
        return NULL;

    return Py_BuildValue( "i", a + b );
}

static PyMethodDef PydMathMethod[] =
{
    { "Add", Add, METH_VARARGS, "Execute add operation." },
    { "Sub", Sub, METH_VARARGS, "Execute sub operation." },
    { "Log", Log, METH_VARARGS, "Execute log operation." },
    { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC initPydMath( void )
{
    PyObject *m = Py_InitModule( "PydMath", PydMathMethod );
    if (m == NULL)
        return;
}

编译后生成“PydMath.dll”的文件,改名为 “PydMath.pyd”,这样python就可以import此扩展模块。import结果如下:


四、Python调用扩展测试

python测试代码如下:

import PydMath
ret = PydMath.Add( 2, 3 )
print ret    
ret = PydMath.Sub( 2, 3 )
print ret
ret = PydMath.Log( "python" )
print ret
运行结果如下:


至此,python的扩展已完工,更多的python扩展内容可参考python的手册“Extending and Embedding”一章。

顺便提下,在写博文的时候chrome崩溃了,写的内容没保存,重启恢复页面后,所写的内容都在,让人心情大落大起呀,该说chrome啥好呢。。。哈哈。。。

转载于:https://my.oschina.net/sunlimpid/blog/137731

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值