python:ctypes,argtypes会自动调用构造函数吗?

2024-05-20 00:38:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有代码,但我不知道为什么它工作。你知道吗

str2payload = lib3.str2payload
str2payload.argtypes = [POINTER(mbuf_t), POINTER(c_char)]

# sbuf = ..
val = b"asdfasdfasdhfjkasgdfjasgdfhjasgdfjhasgdfjhasgdfgjh"
rmr_str2payload(sbuf, val)

这和预期的一样。在这里,val只是python中的一个bytes对象。但是,函数签名表示它应该是POINTER(c_char)。那么什么是魔法转换呢?你知道吗

顺便说一句,我之所以使用POINTER(c_char),是因为它在这里说:https://docs.python.org/3.7/library/ctypes.html#ctypes.c_char_p


Tags: 对象函数代码bytesvalctypescharpointer
1条回答
网友
1楼 · 发布于 2024-05-20 00:38:05

ctypes documentation

When a foreign function is called, each actual argument is passed to the from_param() class method of the items in the argtypes tuple, this method allows adapting the actual argument to an object that the foreign function accepts. For example, a c_char_p item in the argtypes tuple will convert a unicode string passed as argument into a byte string using ctypes conversion rules.

New: It is now possible to put items in argtypes which are not ctypes types, but each item must have a from_param() method which returns a value usable as argument (integer, string, ctypes instance). This allows defining adapters that can adapt custom objects as function parameters.

相关问题 更多 >