【问题标题】:Cython: How to expose void* and function pointer in struct?Cython:如何在结构中公开 void* 和函数指针?
【发布时间】:2014-02-19 09:30:16
【问题描述】:

我有一个 C 头文件:

typedef struct
{    
      <normal members>
      void (*cb_func)(glp_tree *T, void *info);
      void *cb_info;
      <normal members>
} glp_iocp;

目前,在我的 pxd 文件中:

ctypedef struct IntOptCP "glp_iocp":
    <normal members>
    int out_dly     #  mip.out_dly (milliseconds)
    #void (*cb_func)(Tree* tree, void* info)
                    #  mip.cb_func
    #void* cb_info   #  mip.cb_info
    <normal members>

在 pyx 文件中,有时我会(基本上)这样做:

cdef class MyClass:

    IntOptCP _iocp

    <__cintit__ and the like>

    def some_method(self):
        <manipulation of self._iocp>
        controls = dict()
        controls = self._iocp
        return controls

这很好用。不过,现在我也想曝光cb_funccb_info。然后,这会中断对控件的分配。我想要的是两种python对象类型(类?),一种用于cb_func,一种用于cb_info,其实例可以传递给glp_iocp结构的cb_funccb_info参数.

我已阅读 https://github.com/cython/cython/tree/master/Demos/callback(并使用过 pycapsule),但我对 Cython 太缺乏经验/不熟悉,无法了解如何将这些信息用于我的具体案例。

因此,欢迎任何有关如何(最好)公开cb_funccb_info 的帮助和指示。

【问题讨论】:

    标签: python pointers function-pointers cython


    【解决方案1】:

    看来你可以公开cb_funccb_info 做类似于这个玩具示例的事情:

    import numpy as np
    cimport numpy as np
    
    ctypedef void (*f_type)(int, double*, double*)
    
    ctypedef struct IntOptCP:
        int a
        double *b
        double *c
        f_type f
    
    cdef class MyClass:
        cdef IntOptCP _iocp
        def exec_f(self):
            self._iocp.f(self._iocp.a, self._iocp.b, self._iocp.c)
    
    cdef void myfunc(int a, double *b, double *c):
        cdef int i
        for i in range(a):
            b[i] += 1
            c[i] += 1
    
    def main():
        cdef f_type f
        cdef np.ndarray[np.float64_t, ndim=1] b, c
        cdef int a
        a = 100
        b = np.zeros(a, dtype=np.float64)
        c = np.zeros(a, dtype=np.float64)
        test = MyClass()
        test._iocp.a = a
        test._iocp.b = &b[0]
        test._iocp.c = &c[0]
        test._iocp.f = myfunc
        print 'before', a, b, c
        test.exec_f()
        print 'after', a, b, c
    

    【讨论】:

    • 根据您的指示,我设法制定了一些内容以便编译。实际测试代码可能需要一段时间,所以您必须耐心等待我才能选择此作为接受的答案。
    • @equaeghe 希望您有时间测试答案...让我知道您的反馈。
    • 还没有。我会接受你的回答;即使我找不到时间对它们进行充分评估,您的努力也值得认可。
    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 2014-01-13
    • 2013-03-05
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    相关资源
    最近更新 更多