Extest.c文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Python.h"
#define BUFSIZE 10
int fac(int n) {
if (n < 2)
return 1;
return n * fac(n - 1);
}
char *reverse(char *s) {
register char t;
char *p = s;
char *q = (s + (strlen(s) - 1));
while (p < q) {
t = *p;
*p++ = *q;
*q-- = t;
}
return s;
}
static PyObject *
Extest_fac(PyObject *self, PyObject *args) {
int res;
int num;
PyObject* retval;
res = PyArg_ParseTuple(args, "i", &num);
if (!res) {
return NULL;
}
res = fac(num);
retval = (PyObject *)Py_BuildValue("i", res);
return retval;
}
static PyObject *
Extest_reverse(PyObject *self, PyObject *args) {
char *orignal;
if (!(PyArg_ParseTuple(args, "s", &orignal))) {
return NULL;
}
return (PyObject *)Py_BuildValue("s", reverse(orignal));
}
static PyObject *
Extest_doppel(PyObject *self, PyObject *args) {
char *orignal;
char *resv;
PyObject *retval;
if (!(PyArg_ParseTuple(args, "s", &orignal))) {
return NULL;
}
retval = (PyObject *)Py_BuildValue("ss", orignal, resv=reverse(strdup(orignal)));
free(resv);
return retval;
}
static PyMethodDef
ExtestMethods[] = {
{"fac", Extest_fac, METH_VARARGS},
{"doppel", Extest_doppel, METH_VARARGS},
{"reverse", Extest_reverse, METH_VARARGS},
{NULL, NULL},
};
void initExtest() {
Py_InitModule("Extest", ExtestMethods);
}
int main() {
char s[BUFSIZE];
printf("4! == %d
", fac(4));
printf("8! == %d
", fac(8));
printf("12! == %d
", fac(12));
strcpy(s, "abcdef");
printf("reversing 'abcdef', we get '%s'
", reverse(s));
strcpy(s, "madam");
printf("reversing 'madam', we get '%s'
", reverse(s));
return 0;
}
修改python安装目录下Libdistutilsmsvc9compiler.py文件(如有必要可能msvccompiler.py文件也需要做相应更改,视系统而定),找到get_build_version方法直接return 9.0
然后再找到find_vcvarsall方法直接返回vcvarsall.bat的路径(以自己机器安装后的路径为准)
return r'C:UsersAdministratorAppDataLocalProgramsCommonMicrosoftVisual C++ for Python9.0vcvarsall.bat' 两个改变都加载文档子字符串后就可以
创建setup.py文件 输入内容如下:
#!/usr/bin/env python
from distutils.core import setup, Extension
MOD = 'Extest'
setup(name=MOD, ext_modules=[Extension(MOD, sources=['Extest.c'])])
然后在Visual C++ for Python 相应的prompt中输入python setup.py build 就可以构建c和python版的库文件了或python setup.py install
当然也可以建立一个windows的二进制包
python setup.py bdist_wininst