含有章节索引的中文 文章模板

::-- hoxide [2005-03-10 09:16:46]

Python 和 c/c++混编

方式对比

{{{k <[email protected]> reply-to [email protected], to [email protected], date Sat, Mar 22, 2008 at 1:10 PM subject [CPyUG:44155] Re: 谁用过swig }}}

我大概看了一下,感觉Pyrex没有swig方便,有可能是我对Pyrex不熟悉造成的 几种扩展方法:

c扩展代码在windows中的编译

使用minGW

   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,你可以看一下 C语言写Python extension实践


在win下编译并不麻烦,用vc的编译器就可以,python自带的文档里有说明 例如:

cl /LD spam.c c:\python24\libs\python24.lib

这样就可以得到编译后的DLL了

恩, 不错, 收下, 谢谢天成, limodou的blog我也看了, 我试试~~, 计划在这里汇集所有方法~~ --- hoxide

PythonExtendingAndEmbedding (last edited 2009-12-25 07:14:14 by localhost)