gpt4 book ai didi

python - 传递带有指向 ctypes 中其他结构的指针的结构

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:32 25 4
gpt4 key购买 nike

我正在尝试使用 ctypes 为 C 库制作一个 python 包装器。该库具有需要传递指向结构的指针的函数,该结构充当 future 调用的句柄。

这个结构有指向另一个内部结构的指针,这个内部结构进一步有指向其他结构的指针。

typedef struct varnam {

char *scheme_file;
char *suggestions_file;
struct varnam_internal *internal;

} varnam;

varnam_internal 结构有指向 sqlite 数据库等的指针

struct varnam_internal
{
sqlite3 *db;
sqlite3 *known_words;

struct varray_t *r;
struct token *v;
...
}

根据 this,我尝试忽略 varnam_internal 结构所以回答。有点像

class Varnam(Structure):
__fields__ = [("scheme_file",c_char_p),
("suggestions_file",c_char_p),("internal",c_void_p)]

但这似乎不起作用,因为我认为库需要分配 varnam_internal 才能正常运行。

我应该在 python 中实现所有依赖结构吗? ctypes 是否适合像这样包装库?我已经阅读过像 Cython 这样的替代品,但我没有使用 Cython 的经验,所以这可行吗?

最佳答案

没有理由在 ctypes 中定义 varnam_internal 结构,因为您不需要访问它。无论您是否定义结构,您调用的库都会分配它。无论您遇到什么问题,都不是因为您没有在 ctypes 中定义结构。

确保您正确调用了 varnam_init。它使用指向指针的指针作为参数,这意味着您不能直接使用 Varnam 类。你会想要做这样的事情:

from ctypes import *

class Varnam(Structure):
__fields__ = [("scheme_file",c_char_p),
("suggestions_file",c_char_p),
("internal",c_void_p)]

varnam_ptr = POINTER(Varnam)

libvarnam = cdll.LoadLibrary("libvarnam.so") # on Linux
# libvarnam = cdll.libvarnam # on Windows

varnam_init = libvarnam.varnam_init
varnam_init.argtypes = [c_char_p, POINTER(varnam_ptr), POINTER(c_char_p)]

def my_varnam_init(scheme_file):
handle = varnam_ptr()
msg = c_char_p()
r = varnam_init(scheme_file. handle.byref(), msg.byref())
if r != 0:
raise Exception(msg)
return handle

以上代码完全未经测试,但向您展示了应该如何调用 varnam_init

关于python - 传递带有指向 ctypes 中其他结构的指针的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com