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

标签 python ctypes

我有有效的代码,但我不知道它为什么有效。

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

最佳答案

来自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.

关于python:ctypes,argtypes 会自动调用构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55053014/

相关文章:

python - Flask 和 SQLAlchemy 以及 MetaData 对象

python - 将 Python 列表传递给嵌入式 Rust 函数

python - 使用 python 运行未导出的 .dll 函数

c - 使用 ctypes 从 Python 中的 C 函数返回的结构中访问数据

linux - 无法为 ctypes 设置环境变量(python 的 c 库)

linux - os.read 在 inotify 文件描述符 : reading 32 bytes works but 31 raises an exception 上

python - python中无符号整数的指针

python - 有没有办法用 matplotlib 将 3D 线绘制为一系列圆圈?

python - 如何将高斯函数分割为等体积部分

python - 将for循环转换为递归[查找连续的工作日]