You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cython技术问题:如何将Python包装类生成的指针传入C函数?

问题分析与修复方案

你的编译错误有两个核心原因:

  1. 拼写错误:调用方法时写成了new_strct(),实际定义的方法是new_struct(),名称不匹配。
  2. Cython类型访问限制:outer_function是纯Python函数(def定义),Cython默认将其中的wrapper_class视为普通Python对象,无法直接访问扩展类的cdef私有属性_ptr,这就是Cannot convert Python object to 'my_c_struct *'错误的来源。

以下是几种可行的修复方案:


方案一:将outer_function改为Cython级函数

把outer_function定义为cdef或cpdef函数,这样就能直接访问扩展类的cdef属性:

cdef inner_function(my_c_struct *pointer):
    return pointer.a + pointer.b

# cpdef允许函数同时被Python和Cython代码调用,cdef仅支持Cython内部调用
cpdef int outer_function():
    cdef WrapperClass wrapper_class = WrapperClass.new_struct()  # 修正拼写错误
    result = inner_function(wrapper_class._ptr)
    return result

方案二:给WrapperClass添加公开的指针获取方法

如果需要保留outer_function为纯Python函数,可以在WrapperClass中新增一个方法暴露内部指针(注意:此方法需谨慎使用,避免误用指针导致内存问题):

cdef class WrapperClass:
    # ... 原有代码保持不变 ...
    def get_ptr(self):
        """返回内部C结构体指针(仅用于信任的场景)"""
        return self._ptr

然后修改outer_function:

cdef inner_function(my_c_struct *pointer):
    return pointer.a + pointer.b

def outer_function():
    wrapper_class = WrapperClass.new_struct()  # 修正拼写错误
    cdef my_c_struct *ptr = wrapper_class.get_ptr()
    result = inner_function(ptr)
    return result

方案三:在纯Python函数内声明变量类型

在outer_function内部用cdef明确指定wrapper_class的类型,让Cython识别它是WrapperClass实例,从而允许访问cdef属性:

cdef inner_function(my_c_struct *pointer):
    return pointer.a + pointer.b

def outer_function():
    cdef WrapperClass wrapper_class = WrapperClass.new_struct()  # 修正拼写+声明类型
    result = inner_function(wrapper_class._ptr)
    return result

内容的提问来源于stack exchange,提问作者Forrest Williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 08:35:07