- 论坛徽章:
- 0
|
Extest2.c
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- int fac(int n)
- {
- if (n < 2) return(1);
- return (n)*fac(n-1);
- }
- char *reverse(char *s)
- {
- register char t,
- *p = s,
- *q = ( s + ( strlen(s) - 1 ) );
- while ( s && ( p < q ) )
- {
- t = *p;
- *p++ = *q;
- *q-- = t;
- }
- return s;
- }
- int test()
- {
- char s[BUFSIZ];
- printf("4! == %d\n", fac(4));
- printf("8! == %d\n", fac(8));
- printf("12! == %d\n", fac(12));
- strcpy(s, "abcdef");
- printf("reversing 'abcdef', we get '%s'\n", reverse(s));
- strcpy(s, "madam");
- printf("reversing 'madam', we get '%s'\n", reverse(s));
- return 0;
- }
- #include "Python.h"
- static PyObject *
- Extest_fac( PyObject *self, PyObject *args )
- {
- int num;
- if ( !PyArg_ParseTuple(args, "i", &num) )
- {
- return NULL;
- }
- return (PyObject*)Py_BuildValue( "i", fac(num) );
- }
- static PyObject *
- Extest_doppel( PyObject *self, PyObject *args )
- {
- char *orig_str;
- char *dupe_str;
- PyObject* retval;
- if ( !PyArg_ParseTuple(args, "s", &orig_str) )
- {
- return NULL;
- }
- retval = (PyObject*)Py_BuildValue( "ss", orig_str, \
- dupe_str = reverse(strdup(orig_str)) );
- free(dupe_str);
- return retval;
- }
- static PyObject *
- Extest_test(PyObject *self, PyObject *args)
- {
- test();
- return (PyObject*)Py_BuildValue("");
- }
- static PyMethodDef
- ExtestMethods[] =
- {
- { "fac", Extest_fac, METH_VARARGS },
- { "doppel", Extest_doppel, METH_VARARGS },
- { "test", Extest_test, METH_VARARGS },
- { NULL, NULL },
- };
- void initExtest()
- {
- Py_InitModule("Extest", ExtestMethods);
- }
复制代码
编译运行(有警告,暂时忽略 ):
zhou@zhou-desktop:~/Test$ python setup.py build
running build
running build_ext
building 'Extest' extension
creating build
creating build/temp.linux-i686-2.5
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.5 -c Extest2.c -o build/temp.linux-i686-2.5/Extest2.o
Extest2.c:27: 警告: 函数声明不是一个原型
Extest2.c:86: 警告: 函数声明不是一个原型
creating build/lib.linux-i686-2.5
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions build/temp.linux-i686-2.5/Extest2.o -o build/lib.linux-i686-2.5/Extest.so
[ 本帖最后由 MePython 于 2008-7-25 19:46 编辑 ] |
|