抱歉,我通常很难阅读当前的 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/