2008-06-29

c扩展python实战

关键字: c扩展python

    以下内容不是适合python高手看,仅仅是为第一次看<c扩展python >引路.希望中国的孩子不要迷路.

    看了很多人的<c扩展python>,写的非常的精彩.可是却少了实际操作.这些人,都把我们当成了c高手来对待.在编译的时候仅仅是一笔带过.说什么把模块编译连接 之后就可以使用.他却不知道我是那么的菜.

    而且还给出了使用例子:

    >>import foo

    >>foo.bar( '11111' )

    5

    如果觉得自己已经了解了如何编译成python可以使用的东西,那么就不浪费你的宝贵的时间看下去了,而是给我投以鄙视的目光:这么简单的问题,还那来说.

    下面给出例子:在我的linux板块下有<Linux动态链接库编程入门>.

 

  /*foomain.c*/

#include <python2.4/Python.h>
/* Define the method table. */
static PyObject *foo_bar(PyObject *self, PyObject *args);
static PyMethodDef FooMethods[] = {
   {"bar",  foo_bar, METH_VARARGS},
   {NULL, NULL}
};
/* Here's the initialization function.  We don't need to do anything
 *    for our own needs, but Python needs that method table. */
void initfoo()
{
   (void) Py_InitModule("foo", FooMethods);
}
/* Finally, let's do something ... involved ... as an example function. */
static PyObject *foo_bar(PyObject *self, PyObject *args)
{
   char *string;
   int   len;
   if (!PyArg_ParseTuple(args, "s", &string))
       return NULL;
   len = strlen(string);
   return Py_BuildValue("i", len);
}

 

在linux下的运行: gcc -fPIC -shared -o foo.so foomain.c 这一段就ok了.

当前目录下会出现"foo.so"文件.这就是我们一直不明白那些作者说的东西.

现在在到前面python运行环境下去调用就好了(淡黄区域标示处),不会到了这一步好要我给重复给出示例吧?

评论
发表评论

您还没有登录,请登录后发表评论