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

::-- hoxide [DateTime(2005-03-10T09:16:46Z)] TableOfContents

Python 和 c混编

简述

c扩展代码在windows中的编译

   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'