Cython:如何在struct中公开void *和函数指针? [英] Cython: How to expose void* and function pointer in struct?

查看:362
本文介绍了Cython:如何在struct中公开void *和函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C头文件:

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

当前,在我的pxd文件中:

Currently, in my pxd file:

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文件中,我有时(基本上)这样做:

In a pyx file, at some point, I do (essentially):

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自变量

This works nicely. However, now I also wish to expose cb_func and cb_info. This then breaks the assignment to controls. What I would like to have is two python object types (classes?), one for cb_func and one for cb_info, instances of which can be passed through to cb_func and cb_info arguments of the glp_iocp struct.

我已阅读 https://github.com/cython/cython/tree /master/Demos/callback (并使用过pycapsule),但是,我对Cython经验不足/不熟悉,无法了解如何针对具体情况使用该信息.

I have read https://github.com/cython/cython/tree/master/Demos/callback (and have used pycapsule), but nevertheless, I am too inexperienced/unfamiliar with Cython to see how I can use that information for my specific case.

因此,欢迎(最好)公开cb_funccb_info的任何帮助和指针.

So, any help and pointers on how to (best) expose cb_func and cb_info are welcome.

推荐答案

似乎您可以暴露cb_funccb_info来执行类似于此玩具示例的操作:

It seems you can expose cb_func and cb_info doing something similar to this toy example:

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

这篇关于Cython:如何在struct中公开void *和函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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