Cython:基于调用签名的通用函数接口函数

发布于 2025-01-13 05:03:03 字数 493 浏览 1 评论 0原文

基本上,想要编写两个函数,然后使用第三个通用函数,该函数纯粹根据给定的输入参数选择使用给定参数调用两个原始函数中的哪一个。例如

cdef fun1(int a):
    #do something

cdef fun1(float a):
    #do something

#roughly stealing syntax from fortran (this is the part I don't know how to do)
interface generic_function:
    function fun1
    function fun2


#Calling the functions
cdef int a = 2
cdef float b = 1.3
generic_function(a) #runs fun1
generic_function(b) #runs fun2

,显然我可以使用 if 语句来做到这一点,但这对我来说似乎效率不高。 感谢任何和所有的帮助,干杯。

Basically, want to write two functions, then use a third generic function which purely selects which of the two original functions to call with the given arguments based on the input arguments given. eg

cdef fun1(int a):
    #do something

cdef fun1(float a):
    #do something

#roughly stealing syntax from fortran (this is the part I don't know how to do)
interface generic_function:
    function fun1
    function fun2


#Calling the functions
cdef int a = 2
cdef float b = 1.3
generic_function(a) #runs fun1
generic_function(b) #runs fun2

Obviously I could do this with if statements, but that doesn't appear efficient to me.
Any and all help is appreciated, cheers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑红尘 2025-01-20 05:03:03

这可以使用 [fused types] (https://cython. readthedocs.io/en/latest/src/userguide/fusedtypes.html

ctypedef fused int_or_float:
    int
    float

cdef generic_function(int_or_float a):
    if int_or_float is int:
        fun1(a)
    else:
        fun2(a)

if 语句在 Cython 编译函数时进行评估(您可以通过查看生成的 c 代码来验证这一点),因此不是性能问题。

This can be done with [fused types] (https://cython.readthedocs.io/en/latest/src/userguide/fusedtypes.html)

ctypedef fused int_or_float:
    int
    float

cdef generic_function(int_or_float a):
    if int_or_float is int:
        fun1(a)
    else:
        fun2(a)

The if statement is evaluated when Cython compiles the functions (you can verify this by looking at the generated c code) so is not a performance issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文