且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

缓冲区和Memoryview对象的非C程序员解释

更新时间:2023-10-26 14:37:52

下面是一个哈希函数,我写了一行:

Here's a line from a hash function I wrote:

M = tuple(buffer(M, i, Nb) for i in range(0, len(M), Nb))

这将在很长的字符串,男,分裂成较短的长度NB,其中,Nb是字节/字符我可以同时处理数'串'。它这样做是不复制字符串的任何部分,就好像我做了串片,像这样会发生:

This will split a long string, M, into shorter 'strings' of length Nb, where Nb is the number of bytes / characters I can handle at a time. It does this WITHOUT copying any parts of the string, as would happen if I made slices of the string like so:

M = tuple(M[i*Nb:i*Nb+Nb] for i in range(0, len(M), Nb))

我现在可以遍历在M就像我曾经我切片它:

I can now iterate over M just as I would had I sliced it:

H = key
for Mi in M:
    H = encrypt(H, Mi)

基本上,缓冲区和memoryviews是有效的方法来处理字符串Python中的不变性,和切片等。memoryview就像一个缓冲,但你也可以写它的一般复制行为,而不仅仅是阅读。

Basically, buffers and memoryviews are efficient ways to deal with the immutability of strings in Python, and the general copying behavior of slicing etc. A memoryview is just like a buffer, except you can also write to it, not just read.

虽然主缓冲区/ memoryview文档是关于C实现,标准类型页面有下memoryview大量资讯:的 http://docs.python.org/library/stdtypes.html#memoryview-type

While the main buffer / memoryview doc is about the C implementation, the standard types page has a bit of info under memoryview: http://docs.python.org/library/stdtypes.html#memoryview-type

编辑:在我的书签发现这个,http://webcache.googleusercontent.com/search?q=cache:Ago7BXl1_qUJ:mattgattis.com/2010/3/9/python-memory-views+site:mattgattis.com+python&hl=en&client=firefox-a&gl=us&strip=1是一个非常好的简短的归纳。

Found this in my bookmarks, http://webcache.googleusercontent.com/search?q=cache:Ago7BXl1_qUJ:mattgattis.com/2010/3/9/python-memory-views+site:mattgattis.com+python&hl=en&client=firefox-a&gl=us&strip=1 is a REALLY good brief writeup.

编辑2:原来我从该链接何时一个memoryview使用? 摆在首位,这个问题从来没有详细回答的链接已经死了,所以希望这有助于。

Edit 2: Turns out I got that link from When should a memoryview be used? in the first place, that question was never answered in detail and the link was dead, so hopefully this helps.