1.新建fun.c文件和fun.h文件
#include
#include
#include
int fac(int n)
{
if(n < 2)
return 1;
return n * fac(n-1);
}
char *reverse(char *s)
{
char t, *p = s,*q=(s+(strlen(s)-1));
while(s && (p
t = *p;
*p++ = *q;
*q-- = t;
}
return s;
}
int test(void)
// int main(void)
{
char s[1024];
printf("4!==%d\n",fac(4));
printf("8!==%d\n",fac(8));
strcpy(s,"arthas");
printf("reversing 'arthas',we get '%s'\n",reverse(s));
return 0;
}
#ifndef FUN_H_
#define FUN_H_
int fac(int n);
char *reverse(char *s);
int test(void);
#endif
2.新建funwrapper.c文件
#include "Python.h"
#include
#include
#include "fun.h"
static PyObject *fun_fac(PyObject *self,PyObject *args)
{
int num;
if(!PyArg_ParseTuple(args,"i",&num))
return NULL;
return (PyObject*)Py_BuildValue("i",fac(num));
}
static PyObject *fun_reverse(PyObject *self,PyObject *args)
{
char *src;
char *mstr;
PyObject *retval;
if(!PyArg_ParseTuple(args,"s",&src))
return NULL;
mstr = malloc(strlen(src)+1);
strcpy(mstr,src);
reverse(mstr);
retval = (PyObject*)Py_BuildValue("ss",src,mstr);
free(mstr);
return retval;
}
static PyObject *fun_test(PyObject *self,PyObject *args)
{
return (PyObject*)Py_BuildValue("i",test());
}
static PyMethodDef funMethods[] = {
{"fac",fun_fac,METH_VARARGS},
{"reverse",fun_reverse,METH_VARARGS},
{"test",fun_test,METH_VARARGS},
{NULL,NULL},
};
void initfun(void)
{
Py_InitModule("fun",funMethods);
}
3.CMD使用指令
setup.py install build
这里我出错了python Unable to find vcvarsall.bat 错误,
参考上一篇日志python Unable to find vcvarsall.bat 错误解决方法。解决了。
然后生成出fun.pyd文件
4.复制到python的DLLS文件夹下
5.可以用python调用了
import fun
print fun.fac(4)
print fun.reverse("arthas")
fun.test()
6.输出的结果
···
24
('arthas', 'sahtra')
4!24
8!40320
reversing 'arthas',we get 'sahtra'
···