Python ctypes:如何修改现有的char *数组 [英] Python ctypes: How to modify an existing char* array

查看:168
本文介绍了Python ctypes:如何修改现有的char *数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用libupnp的Python应用程序,它是一个C库.我正在使用CTypes使用足够容易的库.我遇到的问题是在为读取请求注册回调函数时.该函数具有以下形式的原型:

I'm working on a Python application that makes use of libupnp which is a C library. I'm using CTypes to use the library which is easy enough. The problem I'm having is when I'm registering a callback function for read requests. The function has a prototype of the following form:

int read_callback(void *pFileHandle, char *pBuf, long nBufLength);

pFileHandle只是一些文件句柄类型. pBuf是可写的内存缓冲区.这是数据输出的地方. nBufLength是要从文件读取的字节数.返回状态码.

pFileHandle is just some file handle type. pBuf is a writable memory buffer. This is where the data is output. nBufLength is the number of bytes to read from the file. A status code is returned.

我为此有一个Python函数指针.这样做很容易,但是当我定义一个Python函数来处理此回调时,我发现pBuf不会被写入,因为Python字符串是不可变的,当您分配或修改它们时,它们会创建新的实例.这带来了一个大问题,因为当函数完成所请求的文件数据时,C库期望返回char指针.尽管由于Python字符串的原因,缓冲区最终每次都为空.在不修改C库的情况下是否可以解决此问题?

I have a Python function pointer for this. That was easy enough to make but when I define a Python function to handle this callback I've found that pBuf doesn't get written to because Python strings are immutable and when you assign or modify them they create new instances. This poses a big problem because the C library expects the char pointer back when the function finishes with the requested file data. The buffer ends up being empty every time though because of the way Python strings are. Is there some way around this without modifying the C library?

处理程序应修改给定的缓冲区参数,这是我的问题.

The handler should modify the buffer parameter that is given which is my problem.

所以我想发生的事情是调用Python函数来执行某些文件的读取(可能在内存中,文件系统句柄或两者之间的任何内容). pBuf参数由流的读取填充(同样在Python中).然后,回调将返回写入了pBuf的C代码.

So what I want to have happen is that the Python function gets called to perform a read of some file (could be in memory, a file system handle, or anything in between). The pBuf parameter is populated by a read of the stream (again in Python). The callback then returns to the C code with pBuf written to.

推荐答案

ctypes可以分配您的C库应该能够写入的缓冲区对象:

ctypes can allocate a buffer object that your C library should be able to write to:

import ctypes
init_size = 256
pBuf = ctypes.create_string_buffer(init_size)

请参阅: http://docs.python.org/2/library/ctypes.html#ctypes.create_string_buffer

这篇关于Python ctypes:如何修改现有的char *数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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