如何多次使用ctypes recv_into C缓冲区? [英] How do I use ctypes to recv_into a C buffer multiple times?

查看:111
本文介绍了如何多次使用ctypes recv_into C缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python库,该库使用 ctypes 向C库注册回调。回调的签名为:

I have a Python library that is using ctypes to register a callback with a C library. The signature of the callback is:

CFUNCTYPE(c_int_32, c_uint_32, POINTER(c_byte), POINTER(c_size_t))

在这种情况下,第三个参数是指向C库分配的字节数组的指针,而第四个参数是它的长度。

In this case, the third argument is a pointer to a byte array allocated by the C library, and the fourth argument is its length.

我想通过调用 socket.recv_into 。更重要的是,我想完全填充这个字节数组:也就是说,如果 recv_into 返回的字节数少于该函数的第四个参数,那么我'想再次调用 recv_into

I would like to populate the byte array with data from the network by calling socket.recv_into. More importantly, I would like to completely fill this byte array: that is, if recv_into returns fewer bytes than the fourth argument of this function then I'd like to call recv_into again.

假设我的函数如下:

def callback(first, second, buffer, size):
    total_read = 0
    while total_read < size[0]:
        total_read += some_socket.recv_into(buffer, size[0] - total_read)
        # XXX: What happens here???

我的问题是:如何操纵 buffer的值以确保每次对 recv_into 的调用都附加到缓冲区,而不是覆盖以前写入的数据?

My question is: how can I manipulate the value of buffer to ensure that each call to recv_into appends to the buffer, rather than overwriting previously-written data?

推荐答案

以注释为基础,无需中间强制转换:

Building on the comments, without intermediate casting:

# assuming we know OFFSET (where to start copying in the buffer)
# and AMOUNT (how many bytes we will read)
tmp_buf = (ctypes.c_char * size).from_address(ctypes.addressof(buffer.contents))
mview = memoryview(tmp_buf)[OFFSET:AMOUNT]
_ = sock.recv_into(mview, AMOUNT)

buffer.contents 返回指向缓冲区的指针,因此可以使用 ctypes

buffer.contents returns the pointer to the buffer, so its address can be extracted using ctypes

这对我来说很简单,它通过简单的C代码将预分配的缓冲区传递到回调中,该回调已在python代码中注册。

This worked for me in a simple C code that passes a pre-allocated buffer into a callback, that is registered in the python code.

这篇关于如何多次使用ctypes recv_into C缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆