python - 是否可以通过 ctypes 通过引用传递 python 字符串?

标签 python ctypes

抱歉,我通常很难阅读当前的 ctypes 文档...

如果我有一个接受 const char * 指针的 C 函数,并且我知道它既不会修改传入的字符串,也不会保留对它的引用在函数调用中,将指针直接传递给 python 字符串的字节确实很有意义。

ctypes 可以做到这一点吗?或者它只是不受支持吗?我真的必须 create_string_buffer 并将我的字符串复制到其中吗?

最佳答案

Assigning a new value to instances of the pointer types c_char_p, c_wchar_p, and c_void_p changes the memory location they point to, not the contents of the memory block (of course not, because Python strings are immutable):

>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> c_s.value = "Hi, there"
>>> print c_s
c_char_p('Hi, there')
>>> print s                 # first string is unchanged
Hello, World
>>>

You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer function which creates these in various ways. The current memory block contents can be accessed (or changed) with the raw property, if you want to access it as NUL terminated string, use the string property:

说ctypes教程。我从这里收集到的是,只有当该函数可以使用 const char* 时,传入的 python 字符串才有效。请记住,它不会有空终止。

无论如何,我建议使用 create_string_buffer

关于python - 是否可以通过 ctypes 通过引用传递 python 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5576925/

相关文章:

python - 如何在循环中从字典填充数据框

python - 适用于 Python 3.9.1 的表包?

python - 解码 ctypes 结构

python - C++ 和 Python : Pass and return a 2D double pointer array from python to c++

python - 如何构造一个 ctype 结构数组?

python - Ctypes 获取窗口位置

python多处理管理器列表错误: [Errno 2] No such file or directory

python - 是否有使用 matplotlib 指定饼图中标题的位置?

python - 在 python 或 coffeescript 中,为什么 list.append 不返回列表本身?如果是这样,递归可以简单得多

python - 从 Python 3 调用 Windows API 时句柄无效