gpt4 book ai didi

linux - 如何使用 Cython 从 dlfcn.h 中使用 dlsym 加载函数

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:38 26 4
gpt4 key购买 nike

我很困惑如何加载共享对象库函数并将其与 Cython 一起使用。我创建了一个 dlfnc.pxd 文件,如下所示:

#dlfcn.pxd
cdef extern from *:
ctypedef char const_char "const char"

cdef extern from 'dlfcn.h' nogil:
void* dlopen(const_char *filename, int flag)
char *dlerror()
void *dlsym(void *handle, const_char *symbol)
int dlclose(void *handle)

unsigned int RTLD_LAZY
unsigned int RTLD_NOW
unsigned int RTLD_GLOBAL
unsigned int RTLD_LOCAL
unsigned int RTLD_NODELETE
unsigned int RTLD_NOLOAD
unsigned int RTLD_DEEPBIND

unsigned int RTLD_DEFAULT
long unsigned int RTLD_NEXT

和一个测试文件如下

#test.pyx
cimport dlfcn

#load shared object
cdef void *handle = dlfcn.dlopen("/usr/local/lib/librefprop.so",
dlfcn.RTLD_NOW | dlfcn.RTLD_GLOBAL)
if handle == NULL:
print dlfcn.dlerror()
1/0 #raise error still need to implement exception.....

#load function
cdef void *setup_FOR = dlfcn.dlsym(handle, "setup0_")
if setup_FOR == NULL:
print dlfcn.dlerror()
1/0 #raise error and still need to implement exception

#some variables
cdef int nc = 2
cdef char *hfld = "/usr/local/lib/refprop/fluids/WATER.FLD|/usr/local/lib/refprop/fluids/AMMONIA.FLD|"
cdef char *hfmix = '/usr/local/lib/refprop/fluids/HMX.BNC'
cdef char *hrf = 'DEF'
cdef long ierr = 0
cdef char *herr = ''
cdef long lhfld = 10000
cdef long lhfmix = 255
cdef long lhrf = 3
cdef long lherr = 255

#call function
setup_FOR(nc, hfld, hfmix, hrf, ierr, herr, lhfld, lhfmix, lhrf, lherr)

这会导致以下屏幕输出错误test.pyx:29:9:调用非函数类型“void”

我已经为此困惑了整整一个星期,如果有人能就如何进行提供建议,那就太好了。

谢谢

最佳答案

您需要将 void * 转换为函数指针才能调用它。

您可以通过 Cython 函数指针强制转换来实现此目的:

(<void (*)(int, char*, char*, char*, long, char*, long, long, long, long)> setup_FOR)(nc, hfld, hfmix, hrf, ierr, herr, lhfld, lhfmix, lhrf, lherr)

关于linux - 如何使用 Cython 从 dlfcn.h 中使用 dlsym 加载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16097481/

26 4 0
文章推荐: c - 内联与静态内联 c
文章推荐: python - 字典按月中的天数(键)在 python 中排序
文章推荐: html - 为什么内容
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com