我有有效的代码,但我不知道它为什么有效。
str2payload = lib3.str2payload
str2payload.argtypes = [POINTER(mbuf_t), POINTER(c_char)]
# sbuf = ..
val = b"asdfasdfasdhfjkasgdfjasgdfhjasgdfjhasgdfjhasgdfgjh"
rmr_str2payload(sbuf, val)
这按预期工作。在这里,val 只是 python 中的一个字节对象。然而,函数签名表明它应该是一个 POINTER(c_char)
。那么是什么在进行神奇的转换呢?
顺便说一句,我使用 POINTER(c_char)
的原因是因为它在这里说:https://docs.python.org/3.7/library/ctypes.html#ctypes.c_char_p
最佳答案
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.
关于python:ctypes,argtypes 会自动调用构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55053014/