【问题标题】:cTypes C program for create_string_buffer used in pythonpython中使用的create_string_buffer的cTypes C程序
【发布时间】:2022-01-03 10:53:26
【问题描述】:

我正在学习 ctypes。但是在任何地方都没有对 create_string_buffer 的明确解释。 等效的 c 程序是什么?

我们什么时候在c程序中使用create_string_buffer?

from ctypes import *
p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
print(sizeof(p), repr(p.raw))

p = create_string_buffer(b"Hello")     # create a buffer containing a NUL terminated string
print(sizeof(p), repr(p.raw))

print(repr(p.value))

p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
print(sizeof(p), repr(p.raw))

p.value = b"Hi"
print(sizeof(p), repr(p.raw))

你能用任何其他简单的 c 程序及其等效的 python 程序表示来解释 create_string_buffer 吗?

提前致谢。

【问题讨论】:

    标签: python c string buffer ctypes


    【解决方案1】:

    您可以使用create_string_buffer to create mutable memory blocks 并传递给C 函数,该函数需要一个指向接收数据的缓冲区的指针。大多数平台 API 都是这样工作的。还有 Cpython source code contains few usages of create_string_buffer.

    例如,考虑PeekNamedPipe windows API。它具有以下签名。

    BOOL PeekNamedPipe( [在] 处理 hNamedPipe, [out, optional] LPVOID lpBuffer, [在] DWORD nBufferSize, [out, optional] LPDWORD lpBytesRead, [out, optional] LPDWORD lpTotalBytesAvail, [out, optional] LPDWORD lpBytesLeftThisMessage );

    此 API 的第二个参数必须是 mutable buffer

    [out, optional] lpBuffer

    指向接收从管道读取的数据的缓冲区的指针。这 如果没有要读取的数据,参数可以为 NULL。

    要从 python 级别使用此 API,您可以将 create_string_buffer 中继到 construct the mutable buffer filled with NULL bytes 并将其作为第二个参数传递给 PeekNamedPipe 调用。

    buf = ctypes.create_string_buffer(len(msg)) rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), buf, ctypes.sizeof(buf), 无, 无, 无)

    所以一旦PeekNamedPipe 调用成功,缓冲区(buf) 将被填充with the result

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多