在cython类中包装预初始化的指针 [英] Wrapping a pre-initialized pointer in a cython class

查看:99
本文介绍了在cython类中包装预初始化的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个C库,该库使用一个回调函数(callback_function)提供指向我要包装的结构(glp_tree)的指针.

I'm trying to use a C library which uses a callback function (callback_function) to provide a pointer to a struct I'd like to wrap (glp_tree).

使用未在__cinit__中创建的指针初始化实例的正确方法是什么?在cython文档中找不到这种模式的示例.

What is the correct way to initialize an instance with a pointer not created in __cinit__? I can't find an example of this pattern in the cython documentation.

我有一些工作代码(请参见下文),该代码将指针转换为整数并返回,但是我不确定这是一种好习惯/理智.

I have some working code (see below), which casts the pointer to an integer and back, but I'm not sure this is good practice / sane.

cdef extern from "stdint.h":
    ctypedef unsigned long long uint64_t

cdef extern from "glpk.h":
    ctypedef struct glp_tree:
        pass

cdef void callback_func(glp_tree* tree, void *info):
    treeobj = Tree(<uint64_t>tree) // cast to an integer...

cdef class Tree:
    cdef glp_tree* ptr
    def __init__(self, uint64_t ptr):
        self.ptr = <glp_tree*>ptr // ... and back to a pointer

直接传递glp_tree对象似乎可行(尽管这不是我想要做的),但是尝试传递指针会导致编译器错误:

Passing the glp_tree object directly seems to work (although it's not what I want to do), but trying to pass the pointer results in a compiler error:

Cannot convert 'glp_tree *' to Python object

推荐答案

您可以使用自定义的@staticmethod cdef创建实例:

Instead of using __init__/__cinit__ (which always expects Python objects as arguments), you can use a custom @staticmethod cdef to create instances:

cdef class Tree:
    cdef glp_tree* ptr

    def __init__(self, *args):
        raise TypeError('Cannot create instance from Python')

    @staticmethod
    cdef Tree create(glp_tree* ptr):
        obj = <Tree>Tree.__new__(Tree) # create instance without calling __init__
        obj.ptr = ptr
        return obj

这篇关于在cython类中包装预初始化的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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