亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 ctypes 訪問指向內部對象的 typedef 結構指針?

如何使用 ctypes 訪問指向內部對象的 typedef 結構指針?

烙印99 2023-10-11 16:00:46
我在 Python 3.6 中使用 ctypes 與 C 庫交互。其中一個函數啟用庫并將類型定義返回到需要傳遞給后續函數調用的內部對象。這是一個例子:// Type definition of the internal object.typedef struct lib_internal_obj * lib_internal_obj_t;/** * Struct containing the available options for the library */struct lib_options {        char ip[255];                 int bufsize_MB;    };/** Constructor of a lib object. * \return A newly created lib object or NULL if construction failed */extern lib_internal_obj_t    lib_internal_obj_new(struct lib_options * options); /** * Example of how the internal object is used.  * */extern int     lib_get_options(lib_internal_obj_t obj, struct lib_options *options);/** * Destructor of the lib object. */extern void    lib_del(lib_internal_obj_t *obj);我不知道這個對象是如何返回并用Python中的ctypes存儲的。我認為它的工作原理就像 Python 中的普通函數調用一樣。這是我嘗試過的:import ctypes as cclass LIB_OPTIONS(c.Structure):    """Struct containing the available options for the library"""    _fields_ = [        ('ip', c.c_char * 255),        ('bufsize_MB', c.c_int)    ]# Open C libc_lib = c.CDLL('./path/to/lib/lib.so', mode=1)# Set optionslib_opts = LIB_OPTIONS()lib_opts.ip = "192.168.1.1".encode('utf-8')lib_opts.bufsize_MB = 2# Not sure how to handle thislib_object = c_lib.lib_internal_obj_new(c.byref(lib_opts))當我運行這個時,我收到以下錯誤:Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)我很確定這與電話有關clib.lib_internal_obj_new。有沒有辦法返回 typedef 結構并從 ctypes 中正確存儲它。任何幫助是極大的贊賞。
查看完整描述

1 回答

?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

出現問題的常見原因ctypes是沒有定義.argtypes和.restype調用函數。特別是,返回類型默認為 an c_int(通常為 32 位),在 64 位系統上,您的函數將返回 64 位指針。


import ctypes as c


class LIB_OPTIONS(c.Structure):

    """Struct containing the available options for the library"""

    _fields_ = [('ip', c.c_char * 255),

                ('bufsize_MB', c.c_int)]


c_lib = c.CDLL('./test')

c_lib.lib_internal_obj_new.argtypes = c.POINTER(LIB_OPTIONS), # 1-tuple declaring input parameter

c_lib.lib_internal_obj_new.restype = c.c_void_p # generic pointer


lib_opts = LIB_OPTIONS(b'192.168.1.1',2)

lib_object = c_lib.lib_internal_obj_new(c.byref(lib_opts))


查看完整回答
反對 回復 2023-10-11
  • 1 回答
  • 0 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號