標籤:amp include res ret 進位 core svc ram strlen
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\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;
}
修改python安裝目錄下Lib\distutils\msvc9compiler.py檔案(如有必要可能msvccompiler.py檔案也需要做相應更改,視系統而定),找到get_build_version方法直接return 9.0
然後再找到find_vcvarsall方法直接返回vcvarsall.bat的路徑(以自己機器安裝後的路徑為準)
return r‘C:\Users\Administrator\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\vcvarsall.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
Microsoft Visual C++ Compiler for Python 2.7