Python ctypes 和可变性

wrs*_*der 5 python ctypes

我注意到将 Python 对象传递给本机代码ctypes可能会破坏可变性预期。

例如,如果我有一个 C 函数,例如:

int print_and_mutate(char *str)
{
    str[0] = 'X';
    return printf("%s\n", str);
}
Run Code Online (Sandbox Code Playgroud)

我这样称呼它:

from ctypes import *
lib = cdll.LoadLibrary("foo.so")

s = b"asdf"
lib.print_and_mutate(s)
Run Code Online (Sandbox Code Playgroud)

的值已s更改,现在为b"Xsdf"

Python 文档说“但是,您应该小心,不要将它们传递给需要指向可变内存的指针的函数。” .

这仅仅是因为它打破了对哪些类型不可变的预期,还是其他东西会因此而打破?换句话说,如果我清楚地了解我的原始bytes对象会改变,即使通常bytes是不可变的,那是可以的,或者如果我create_string_buffer不像我应该的那样使用我会得到一些令人讨厌的惊喜?

Mar*_*nen 4

Python 对不可变对象做出了假设,因此改变它们肯定会破坏事物。这是一个具体的例子:

>>> import ctypes as c
>>> x = b'abc'          # immutable string
>>> d = {x:123}         # Used as key in dictionary (keys must be hashable/immutable)
>>> d
{b'abc': 123}
Run Code Online (Sandbox Code Playgroud)

现在为不可变对象构建一个 ctypes 可变缓冲区。 id(x)在 CPython 中是 Python 对象的内存地址并sys.getsizeof()返回该对象的大小。PyBytes 对象有一些开销,但对象的末尾有字符串的字节。

>>> sys.getsizeof(x)
36
>>> px=(c.c_char*36).from_address(id(x))
>>> px.raw
b'\x02\x00\x00\x00\x00\x00\x00\x000\x8fq\x0b\xfc\x7f\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\xf0\x06\xe61\xeb\x00\x1b\xa9abc\x00'
>>> px.raw[-4:]  # last bytes of the object
b'abc\x00'
>>> px[-4]
b'a'
>>> px[-4] = b'y'  # Mutate the ctypes buffer, mutating the "immutable" string
>>> x              # Now it has a modified value.
b'ybc'
Run Code Online (Sandbox Code Playgroud)

现在尝试访问字典中的键。使用其哈希值在 O(1) 时间内定位键,但哈希值是原始的“不可变”值,因此它是不正确的。无法再通过旧值或新值找到键:

>>> d           # Note that dictionary key changed, too.
{b'ybc': 123}
>>> d[b'ybc']   # Try to access the key
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: b'ybc'
>>> d[b'abc']   # Maybe original key will work? It hashes same as the original...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: b'abc'
Run Code Online (Sandbox Code Playgroud)