gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:23:07 26 4
gpt4 key购买 nike

抱歉,我通常很难阅读当前的 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 topass them to functions expectingpointers to mutable memory. If youneed mutable memory blocks, ctypes hasa create_string_buffer function whichcreates these in various ways. Thecurrent memory block contents can beaccessed (or changed) with the rawproperty, if you want to access it asNUL terminated string, use the stringproperty:

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

无论如何,我建议使用 create_string_buffer

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com