Python如何建立自定义“内置”函数

众所周知,Python中内置函数和自定义函数不是一个类型,一个是BuiltinFunctionType,一个是FunctionType。而BuiltinFunctionType是不可实例化的,只能由内置模块和扩展模块创建。但是,你们应该知道下面是什么了,只要用一定的技巧,BuiltinFunctionType还是可以实例化的!

Python有一个ctypes模块,用于实现C的数据类型,巧的是,Python的内置类型的底层实现就是C完成的。

所以,我们需要定义BuiltinFunctionType的结构,同时定义它的一个子结构:PyMethodDef。同时也要定义所有Object都适用的结构。

(’’’

import ctypes

class PyObject(ctypes.Structure):

    _fields_ = [('ob_refcnt', ctypes.c_ssize_t), ('ob_type', ctypes.c_void_p)]

Object = ctypes.POINTER(PyObject)
PyCFunction = CFUNCTYPE(ctypes.py_object, Object, Object)

class PyMethodDef(ctypes.Structure):

    _fields_ = [('ml_name', ctypes.c_char_p), ('ml_meth', PyCFunction),

            ('ml_flags', ctypes.c_int), ('ml_doc', ctypes.c_char_p)]

_MethodDef = ctypes.POINTER(PyMethodDef)

class PyBuiltinObject(ctypes.Structure):

    _fields_ = [('ob_refcnt', ctypes.c_ssize_t), ('ob_type', ctypes.c_void_p), ('m_ml', _MethodDef), ('m_self', Object),

                                ('m_module', Object)]

BuiltinObject = ctypes.POINTER(PyBuiltinObject)

’’’)

有些朋友可能注意到我把结构体都兑换成了指针,这是因为其实Python的所有对象都是指针。

下面的步骤是:

1.开一个合法的BuiltinObject,且能被Python感知到;

2.把自定义函数转为C函数;

3.开一个PyMethodDef作为成员,其中的ml_meth为转换得来的C函数;

4.将函数信息填入PyMethodDef和PyBuiltinObject,并将原对象返回。

先说第一步。要开一个能被Python感知到的对象,就不能用C的malloc,而是要用Python创建一个对象,然后把类名标注为BuiltinFunctionType。

(’’’

class Alloc(object):

    __slots__ = map('x{}'.format, range((ctypes.sizeof(PyBuiltinObject)-ctypes.sizeof(PyPbject))/ctypes.sizeof(ctypes.c_void_p)))



def alloc_builtin():

    obj = Alloc()

    stru = ctypes.cast(id(obj), BuiltinObject)

    stru.contents.ob_type = ctypes.c_void_p(id(type(cmp)))

    return (obj, stru)

’’’)

第二步,我需要说明Python内置函数需要的C函数的规则:

BuiltinFunctionType有一个flags成员,就表示它的C函数使用的规则。其中最常用的是METH_VARARGS = 0x0001.

这种规则的函数第一个参数是当这个函数作为方法被调用的self,第二个参数是需要调用的参数包(有点绕口)args。

所以代码如下:

(’’’

def to_target(f):

    CFUNCTYPE = ctypes.CFUNCTYPE

    def target(self, args):

        self = c_py_types.get_object(self)

        args = c_py_types.get_object(args)

        if self == None:

            return f(*args)

        else:

            return f(self, *args)

    return PyCFunction(target)

’’’)

接下来的第三步和第四步没什么难度,我就不赘述了。

源代码如下:

(’’’

import ctypes

class PyObject(ctypes.Structure):

    _fields_ = [('ob_refcnt', ctypes.c_ssize_t), ('ob_type', ctypes.c_void_p)]

Object = ctypes.POINTER(PyObject)
PyCFunction = CFUNCTYPE(ctypes.py_object, Object, Object)

class PyMethodDef(ctypes.Structure):

    _fields_ = [('ml_name', ctypes.c_char_p), ('ml_meth', PyCFunction),

            ('ml_flags', ctypes.c_int), ('ml_doc', ctypes.c_char_p)]

_MethodDef = ctypes.POINTER(PyMethodDef)

class PyBuiltinObject(ctypes.Structure):

    _fields_ = [('ob_refcnt', ctypes.c_ssize_t), ('ob_type', ctypes.c_void_p), ('m_ml', _MethodDef), ('m_self', 
Object),

                                ('m_module', Object)]

BuiltinObject = ctypes.POINTER(PyBuiltinObject)

class Alloc(object):

    __slots__ = map('x{}'.format, range((ctypes.sizeof(PyBuiltinObject)-ctypes.sizeof(PyPbject))/ctypes.sizeof(ctypes.c_void_p)))

def alloc_builtin():

    obj = Alloc()

    stru = ctypes.cast(id(obj), BuiltinObject)

    stru.contents.ob_type = ctypes.c_void_p(id(type(cmp)))

    return (obj, stru)

def to_target(f):

    CFUNCTYPE = ctypes.CFUNCTYPE

    def target(self, args):

        self = c_py_types.get_object(self)

        args = c_py_types.get_object(args)

        if self == None:

            return f(*args)

        else:

            return f(self, *args)

    return PyCFunction(target)

def new_methoddef(name, meth, flags=METH_VARARGS, doc=""):

    malloc = ctypes.cdll.msvcrt.malloc

    malloc.argtypes = (ctypes.c_size_t,)

    malloc.restype = _MethodDef

    p = malloc(ctypes.sizeof(PyMethodDef))

    p.contents = PyMethodDef(name, meth, flags, doc)

    return p

def new_builtin(func, self=None):

    obj, stru = alloc_builtin()

    stru.contents.m_ml = \

        new_methoddef(func.__name__, to_target(func), doc=("" if

            func.__doc__ == None else func.__doc__))

    slf = ctypes.cast(id(self), Object)

    slf.ob_refcnt += 1

    stru.contents.m_self = (ctypes.cast(ctypes.c_void_p(None),

                                      Object) if self == None else

                                      slf)

    mdl = ctypes.cast(id(func.__module__), Object)

    mdl.ob_refcnt += 1

    stru.contents.m_module = mdl

    return obj

if __name__ == "__main__":
    @new_builtin
    def echo(x):print x
    echo("Hello world")

’’’)

你可能感兴趣的:(Python如何建立自定义“内置”函数)