含有章节索引的中文 文章模板
::-- hoxide [2005-03-10 09:16:46]
1. Python 和 c混编
简述
1.1. c扩展代码在windows中的编译
1.1.1. 使用minGW
由于Windows和*nix不同, 不是一个完整的开发环境, 所以要在windows上为python编写c扩展非常麻烦, 如何编译一直是个问题, 以前以为python2.3一定要MSVC6.0才能编译扩展, 因为我没有MSVC, 所以从来没在windows下搞定编译问题.
现在找到一种用minGW编译的方法. 描述如下
例子简化自python manual
1
2 # spam.c
3
4 #include <Python.h>
5
6 static PyObject *
7 spam_a(PyObject *self, PyObject *args)
8 {
9 return Py_BuildValue("i", 1);
10 }
11
12 static PyMethodDef SpamMethods[] = {
13 {"a", spam_a, METH_VARARGS,
14 "Just a example"},
15 {NULL, NULL, 0, NULL} /* Sentinel */
16 };
17
18 static PyObject *SpamError;
19
20
21 PyMODINIT_FUNC
22 initspam(void)
23 {
24 (void) Py_InitModule("spam", SpamMethods);
25 }
26
27 int
28 main(int argc, char *argv[])
29 {
30 /* Pass argv[0] to the Python interpreter */
31 Py_SetProgramName(argv[0]);
32
33 /* Initialize the Python interpreter. Required. */
34 Py_Initialize();
35
36 /* Add a static module */
37 initspam();
38
39 }
40
编译命令:
gcc -c -DBUILD_DLL spam.c -If:/python23/include dllwrap --dllname=spam.dll --driver-name=gcc spam.o f:/python23/libs/python23.lib
ddlwrap会提示说这个不一定是你要的dll
dllwrap: no export definition file provided. Creating one, but that may not be what you want
不用管它, 可以用
>>> import spam >>> dir(spam) ['__doc__', '__file__', '__name__', 'a'] >>> spam.a() 1 >>> spam.a.__doc__ 'Just a example'
我以前写过一篇blog,你可以看一下 C语言写Python extension实践
-- limodou
在win下编译并不麻烦,用vc的编译器就可以,python自带的文档里有说明 例如:
cl /LD spam.c c:\python24\libs\python24.lib
这样就可以得到编译后的DLL了
-- Dreamingk
恩, 不错, 收下, 谢谢天成, limodou的blog我也看了, 我试试~~, 计划在这里汇集所有方法~~ --- hoxide