当dict的void *参数传递函数时,Cython引发错误 [英] Cython throws an error when pass function with void * argument to dict

查看:73
本文介绍了当dict的void *参数传递函数时,Cython引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 void * 参数的函数,我想将其存储在字典中.

I have a function with void * parameter and I want to store it in the dict.

我要做的是:

%%cython

cdef void foo(void * bar):
    pass

cdef dict foobar = {'foo': foo}

但是此代码会引发错误:无法将'void(void *)'转换为Python对象有什么方法可以解决此问题?

But this code raises an Error: Cannot convert 'void (void *)' to Python object Any ways to overcome this problem?

推荐答案

最简单的解决方案是创建一个可以包装此函数的 cdef类.由于 cdef类是Python对象,因此可以像存储其他任何Python对象一样将其存储在字典中.

The easiest solution is to create a cdef class that can wrap this function. Since the cdef class is a Python object it can be stored in a dictionary like any other Python object.

ctypedef void (*void_func_ptr)(void*)

cdef class VoidFuncWrapper:
    cdef void_func_ptr func
    def __cinit__(self):
       self.func = NULL

    @staticmethod
    cdef VoidFuncWrapper make_from_ptr(void_func_ptr f):
        cdef VoidFuncWrapper out = VoidFuncWrapper()
        out.func = f
        return out

然后您可以简单地进行以下操作:

Then you can simply do:

cdef dict foobar = {'foo': VoidFuncWrapper.make_from_ptr(foo)}

这篇关于当dict的void *参数传递函数时,Cython引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆