关闭

用c的写python模块的演示

标签: pythoncmethodsextensionnullinclude
644人阅读 评论(0) 收藏 举报
分类:

引用http://www.douban.com/note/19345973/


用c的写python模块的演示

2008-10-06 14:05:19
不说话,贴代码

uuxx/test.py

________________________

#!/usr/bin/env python

import uuxx
for i in range(111):
    filename=uuxx.uufilename()
    print filename,len(filename)

________________________

uuxx/setup.py
________________________

#!/usr/bin/python

from distutils.core import setup, Extension
setup(
    name = "uuxx",
    version = "1.1",
    author = "zsp",
    author_email = "zsp007@gmail.com",
    url = "http://zsp.javaeye.com",
    description = "uuid for more things",
    license = "GPL",
    classifiers = [
        "License :: GPL",
        "Programming Language :: C++"],
    ext_modules = [
        Extension(
            "uuxx",
            ["uuxx.cpp"],
            include_dirs = ["/usr/include/"],
            libraries = ["uuid","util"]
        )
    ]
    )

________________________


uuxx.cpp
________________________

 

extern "C" {
#include <uuid/uuid.h>
#include <Python.h>
}

void base64_encode(const void * pdata,const unsigned long data_size, void * out_pcode)
{
static const unsigned char base64char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_!" ;

if (data_size <=0 ) return ;

const unsigned char * pS = (const unsigned char *)pdata;
const unsigned char * pSEnd = &pS[data_size];
unsigned char * pD =(unsigned char *)out_pcode;

for (;pS <pSEnd-2 ;pS+=3 ,pD+=4 )
{
pD[0 ] = base64char[pS[0 ]>> 2 ];
pD[1 ] = base64char[0x3F & (pS[0 ] <<4 | pS[1 ]>> 4 )];
pD[2 ] = base64char[0x3F & (pS[1 ] <<2 | pS[2 ]>> 6 )];
pD[3 ] = base64char[0x3F & pS[2 ];
}

//static const unsigned char BASE64_PADDING='=';
switch (pSEnd-pS)
{
case 1 :
pD[0 ]=base64char[pS[0 ]>> 2 ];
pD[1 ]=base64char[0x3F & (pS[0 ] <<4 )];
//pD[2] = BASE64_PADDING;
//pD[3] = BASE64_PADDING ;
break ;
case 2 :
pD[0 ]=base64char[pS[0 ]>> 2 ];
pD[1 ]=base64char[0x3F & (pS[0 ] <<4 | pS[1 ]>> 4 )];
pD[2 ]=base64char[0x3F & (pS[1 ] <<2 )];
//pD[3] = BASE64_PADDING ;
break ;
}
};
PyObject * uufilename(PyObject * args,PyObject *kwds){
    uuid_t uu;
    uuid_generate( uu );

    //用的改造过的base64的编码+改造的uuid

    static const unsigned data_size=16 ;
    static const int b64_length = (data_size+2 )/3 *4 -2 ;
 
    char b64uu[data_size];

    base64_encode(uu,data_size,b64uu);
    PyObject *value = PyString_FromStringAndSize(b64uu,b64_length);
    return value;
};
PyDoc_STRVAR(uufilename__doc__,
    "uufilename"
);
static PyMethodDef uuxx_methods[] = {
  {
    "uufilename" ,
    uufilename,
    METH_VARARGS,
    uufilename__doc__
},
{NULL, NULL, 0 , NULL}

};

PyMODINIT_FUNC inituuxx(){
  Py_InitModule("uuxx" , uuxx_methods);
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:276005次
    • 积分:3522
    • 等级:
    • 排名:第11685名
    • 原创:74篇
    • 转载:20篇
    • 译文:0篇
    • 评论:79条
    文章分类
    最新评论