含有章节索引的中文 文章模板
::-- hoxide [DateTime(2005-03-10T09:16:46Z)] TableOfContents
Python 和 c混编
简述
c扩展代码在windows中的编译
- 由于Windows和*nix不同, 不是一个完整的开发环境, 所以要在windows上为python编写c扩展非常麻烦, 如何编译一直是个问题, 以前以为python2.3一定要MSVC6.0才能编译扩展, 因为我没有MSVC, 所以从来没在windows下搞定编译问题. 现在找到一种用minGW编译的方法. 描述如下 例子简化自python manual
1 # spam.c
2
3 #include <Python.h>
4
5 static PyObject *
6 spam_a(PyObject *self, PyObject *args)
7 {
8 return Py_BuildValue("i", 1);
9 }
10
11 static PyMethodDef SpamMethods[] = {
12 {"a", spam_a, METH_VARARGS,
13 "Just a example"},
14 {NULL, NULL, 0, NULL} /* Sentinel */
15 };
16
17 static PyObject *SpamError;
18
19
20 PyMODINIT_FUNC
21 initspam(void)
22 {
23 (void) Py_InitModule("spam", SpamMethods);
24 }
25
26 int
27 main(int argc, char *argv[])
28 {
29 /* Pass argv[0] to the Python interpreter */
30 Py_SetProgramName(argv[0]);
31
32 /* Initialize the Python interpreter. Required. */
33 Py_Initialize();
34
35 /* Add a static module */
36 initspam();
37
38 }
编译命令:
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,你可以看一下 [http://www.donews.net/limodou/archive/2004/04/12/11800.aspx C语言写Python extension实践]
- -- limodou
在win下编译并不麻烦,用vc的编译器就可以,python自带的文档里有说明 例如:
cl /LD spam.c c:\python24\libs\python24.lib
这样就可以得到编译后的DLL了
- -- Dreamingk