栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

围绕Python函数制作Cython包装器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

围绕Python函数制作Cython包装器

由于历史原因,我保留了我的其他答案-
它表明,不进行jit编译就无法执行您想要的操作,并帮助我了解@DavidW在此答案中)的建议有多么出色。

为了简单起见,我使用功能的签名稍微简单一些,并相信您可以根据需要对其进行更改。

这是关闭的蓝图,它允许

ctypes
在后台进行jit编译:

%%cython#needs Cython > 0.28 to run because of verbatim C-pre cdef extern from *:   #fill some_t with life    """    typedef int (*func_t)(int);    static int some_f(func_t fun){        return fun(42);    }    """    ctypedef int (*func_t)(int)    int some_f(func_t myFunc)#works with any recent Cython version:import ctypescdef class Closure:    cdef object python_fun    cdef object jitted_wrapper    def inner_fun(self, int arg):        return self.python_fun(arg)    def __cinit__(self, python_fun):        self.python_fun=python_fun        ftype = ctypes.CFUNCTYPE(ctypes.c_int,ctypes.c_int) #define signature        self.jitted_wrapper=ftype(self.inner_fun)#jit the wrapper    cdef func_t get_fun_ptr(self):        return (<func_t *><size_t>ctypes.addressof(self.jitted_wrapper))[0]def use_closure(Closure closure):    print(some_f(closure.get_fun_ptr()))

现在使用它:

>>> cl1, cl2=Closure(lambda x:2*x), Closure(lambda x:3*x)>>> use_closure(cl1)84>>> use_closure(cl2)126


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653523.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号