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

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

1. Python 和 c混编

简述

1.1. c扩展代码在windows中的编译

1.1.1. 使用minGW

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


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

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

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

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

last edited 2005-03-11 12:39:02 by hoxide