python版本在我之前一篇blog里http://my.oschina.net/1123581321/blog/220751
代码结构
xorcrypt-0.2
\setup.py
\xorcrypt2.c
\README
setup.py
#!/usr/bin/python from distutils.core import setup, Extension __version__ = "0.2" macros = [('MODULE_VERSION', '"%s"' % __version__)] setup(name = "xorcrypt2", version = __version__, author = "fk", author_email = "[email protected]", url = "", download_url = "", description = "XOR encrypt/decrypt for Python", long_description = open('README').read(), license = "LGPL", platforms = ["Platform Independent"], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules" ], ext_modules = [ Extension(name='xorcrypt2', sources=['xorcrypt2.c'], define_macros=macros) ] )
xorcrypt2.c
#include <Python.h> #include <stdio.h> static PyObject* xor_crypt(PyObject* self, PyObject* args) { char* s; unsigned int key = 0; unsigned int M1 = 0; unsigned int IA1 = 0; unsigned int IC1 = 0; unsigned int size; PyObject* v; char *p; unsigned int i = 0; unsigned char c; // 解析参数 s#表示字符串和它的长度, |后的表示可选参数, I表示unsigned int if(!PyArg_ParseTuple(args, "s#|IIII", &s, &size, &key, &M1, &IA1, &IC1)) return NULL; if(key == 0) key = 1; if(M1 == 0) M1 = 1 << 19; if(IA1 == 0) IA1 = 2 << 20; if(IC1 == 0) IC1 = 3<< 21; // v是python的空字符串, 长度为size v = PyString_FromStringAndSize((char*)NULL, size); if(v == NULL) return NULL; // p是把python的字符串v转换为c的字符串, 对p进行操作也会影响v p = PyString_AS_STRING(v); for (i = 0; i < size; i++) { c = (unsigned char)s[i]; key = IA1 * (key % M1) + IC1; *p = c ^ (unsigned char)((key >> 20)&0xff); p++; } return v; } // 方法列表, 要传到初始化函数里 static PyMethodDef xorcrypt2_methods[] = { // 对应python的模块名.方法名 | 对应的c函数 | METH_VARARGS用来告诉python, crypt是用c实现的 | 函数说明 {"crypt", (PyCFunction)xor_crypt, METH_VARARGS, PyDoc_STR("encrypt/decrypt(string) -> generate the string.")}, {NULL, NULL} // sentinel }; PyDoc_STRVAR(module_doc, "XOR encrypt/decrypt module."); /* 当初始化模块时, 这个函数自动被调用, 函数名要固定为 <init+模块名> */ PyMODINIT_FUNC initxorcrypt2(void) { PyObject *m; m = Py_InitModule3("xorcrypt2", xorcrypt2_methods, module_doc); if (m == NULL) return; PyModule_AddStringConstant(m, "__version__", "0.2"); }
安装(编译)
python setup.py install(build)
套着写就行了
import xorcrypt2 print xorcrypt2.crypt("abc", 2) # 'kde' print xorcrypt2.crypt("kde", 2) # 'abc'
---
测试发现这个c版本的速度是python版本的42倍! 很吃惊