请教C扩展python的编译方式
请问用c写了一个python扩展,
然后按要求写了以下python文件
然后怎么编辑c文件呢?
.c文件需要放到什么目录中去吗?
我把c文件和python文件放入“C:\Python25\include”目录中,执行python文件
ide一直提示这个信息
Traceback (most recent call last):
File "C:\Python25\include\setupExtest2.py", line 4, in <module>
setup(name=MOD,ext_modules=[Extension(MOD,sources=['Extest2.c'])])
File "C:\Python25\lib\distutils\core.py", line 139, in setup
raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
SystemExit: usage: setupExtest2.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setupExtest2.py --help [cmd1 cmd2 ...]
or: setupExtest2.py --help-commands
or: setupExtest2.py cmd --help
error: no commands supplied
以下是c文件'Extest2.c'的内容
// Extestl.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZ 255
int fac(int n)
{
if( n < 2 )return(1);
return(n)*fac(n-1);
}
char *reverse(char *s)
{
register char t,/*中间变量t*/
*p = s,
*q = (s + (strlen(s) - 1));
while( 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));
printf("reversing 'abcdef' , we get '%s'\n", s);
//==> 4! == 24
//==> 8! == 40320
//==> 12! == 479001600
//==> reversing 'abcdef' , we get 'fedcba'
return 0;
}
#include "Python.h"
static PyObject * Extest_doppel(PyObject *self,PyObject *args)
{
char *orig_str;
char *desc_str;
PyObject *relsult;
if(!PyArg_ParseTuple(args,"s",&orig_str))
return NULL;
desc_str = (char*)malloc(sizeof(orig_str));
desc_str = reverse(orig_str);
relsult = (PyObject*)Py_BuildValue("ss",orig_str,desc_str);
free(desc_str);
return relsult;
}
static PyObject * Extest_fac(PyObject *self,PyObject *args)
{
int num;
if (!PyArg_ParseTuple(args,"i",&num))
{
return NULL;
}
return (PyObject*)Py_BuildValue("i",&num);
}
static PyObject * Extest_test(PyObject *self,PyObject *args)
{
test();
return (PyObject *)Py_BuildValue("");
}
static PyMethodDef ExtestMethods[]
{
{"fac",Extest_fac,METH_VARAGES,"fac"},
{"doppel",Extest_doppel,METH_VARAGES,"doppel"},
{NULL,NULL,0,NULL},
};
void initExtest()
{
Py_InitModule("Extest",ExtestMethods);
}
/*int _tmain(int argc, _TCHAR* argv[])
{
return test();
}*/
以下是setupExtest2.py的内容:
from distutils.core import setup,Extension
MOD = 'Extest'
setup(name=MOD,ext_modules=[Extension(MOD,sources=['Extest2.c'])])
[解决办法]
一般脚本的名称写成 setup.py
编译的话,用命令
python setup.py build