您好,欢迎访问一九零五行业门户网

一步步来用C语言来写python扩展

本文介绍如何用 c 语言来扩展 python。所举的例子是,为 python 添加一个设置字符串到 windows 的剪切板(clipboard)的功能。我在写以下代码的时候用到的环境是:windows xp, gcc.exe 4.7.2, python 3.2.3。
第一步 撰写c语言的dll
创建一个 clip.c 文件,内容如下:
// 设置 unicode 库,这样的话才可以正确复制宽字符集 #define unicode #include #include // 设置文本到剪切板(clipboard) static pyobject *setclip(pyobject *self, pyobject *args) { lptstr lptstrcopy; hglobal hglbcopy; py_unicode *content; int len = 0; // 将 python 的 unicode 字符串及长度传入 if (!pyarg_parsetuple(args, u#, &content, &len)) return null; py_incref(py_none); if (!openclipboard(null)) return py_none; emptyclipboard(); hglbcopy = globalalloc(gmem_moveable, (len+1) * sizeof(py_unicode)); if (hglbcopy == null) { closeclipboard(); return py_none; } lptstrcopy = globallock(hglbcopy); memcpy(lptstrcopy, content, len * sizeof(py_unicode)); lptstrcopy[len] = (py_unicode) 0; globalunlock(hglbcopy); setclipboarddata(cf_unicodetext, hglbcopy); closeclipboard(); return py_none; } // 定义导出给 python 的方法 static pymethoddef clipmethods[] = { {setclip, setclip, meth_varargs, set string to clip.}, {null, null, 0, null} }; // 定义 python 的 model static struct pymoduledef clipmodule = { pymoduledef_head_init, clip, null, -1, clipmethods }; // 初始化 python model pymodinit_func pyinit_clip(void) { return pymodule_create(&clipmodule); }
第二步 写 python 的 setup.py
创建一个 setup.py 文件,内容如下:
from distutils.core import setup, extension module1 = extension('clip', sources = ['clip.c']) setup (name = 'clip', version = '1.0', description = 'this is a clip package', ext_modules = [module1])
第三步 用 python 编译
运行以下命令:
python setup.py build --compiler=mingw32 install
在我的环境中会提示以下错误:
gcc: error: unrecognized command line option '-mno-cygwin'
error: command 'gcc' failed with exit status 1
打开 %python安装目录%/lib/distutils/cygwinccompiler.py 文件,将里面的 -mno-cygwin 删除掉,然后再运行即可。
正常运行后,会生成一个 clip.pyd 文件,并将该文件复制到 %python安装目录%/lib/site-packages 目录中
第四步 测试该扩展
写一个 test.py, 内容如下:
# -*- encoding: gbk -*- import clip clip.setclip(hello python)
运行
python test.py
再到任何一个地方粘贴,即可验证是否正确。
其它类似信息

推荐信息