从pyx文件中的cdef函数获取CFUNCTYPEdef函数的地址

问题描述

我正在使用 ctypesgenctypesgen_to_pxd 为给定的本机库生成 ctypes 包装器以及包含这些类型的 pxd。

我可以非常轻松地将生成的 ctypes 包装器用于 call into native code from Python。我无法弄清楚如何做的是通过手写 pyx(见下文)将 Python 回调的函数指针返回到我的本机库,然后它可以调用函数指针来执行一些 Python 代码

这是 Github 上的 complete and runnable sample显示了我的问题。您可以使用提供的 build-and-run.sh 构建它或使用 VS Code remote containers 打开工作区。后一种方法还允许您调试和重新编译,而不是使用 shell script = docker build + run。

cythoncallbacks.pyx.in内容如下供快速参考

# cython: language_level=3

import sys
sys.path.insert(0,'')

from ctypes import *
from nativelib cimport *
import nativelib as n


@CFUNCTYPE(UNCHECKED(n.NativeResult),n.NativeLibHdl)
def python_cfunctype_callback(libHdl) -> n.NativeResult:
    print("Do stuff in a CFUNCTYPE Python function here...")
    return n.NativeResult(n.RESULT_OK)

def python_regular_callback(libHdl: n.NativeLibHdl) -> n.NativeResult:
    print("Do stuff in a regular Python callback here...")
    return n.NativeResult(n.RESULT_OK)

cdef public NativeResult cythoncallbacks_getcallbacks(NativeLibHdl libHdl,CallbackParams params,NativeCallbacksHdl callbacksHdl):
    # How do I call python_cfunctype_callback or python_regular_callback from here?
    # Both ways below won't compile

    ###################################################
    
    # Errors out with
    # Cannot convert Python object to CallbackFunc* or
    # From https://stackoverflow.com/a/33485103/802203
    
    # callbacksHdl.callback = python_cfunctype_callback

    ###################################################
    
    # Errors out with
    # Storing unsafe C derivative of temporary Python reference
    # from https://stackoverflow.com/questions/2038839/python-ctypes-addressof-cfunctype
    
    # callbacktype = CFUNCTYPE(UNCHECKED(n.NativeResult),n.NativeLibHdl)
    # callbacksHdl.callback = callbacktype(python_cfunctype_callback)

    ####################################################################################

    return NativeResult(RESULT_NOT_IMPLEMENTED)

上面 ###################### 行中的部分是我想要弄清楚的。理想情况下,如果可能,我更愿意使用 python_regular_callback,这样我就可以像使用 dlopendlsym 一样动态加载适当的模块方法

提前致谢,总是很高兴澄清或提供更多信息。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)