问题
你要写c扩展来读取来自任何python类文件对象中的数据(比如普通文件、stringio对象等)。
解决方案
要读取一个类文件对象的数据,你需要重复调用 read() 方法,然后正确的解码获得的数据。
下面是一个c扩展函数例子,仅仅只是读取一个类文件对象中的所有数据并将其输出到标准输出:
#define chunk_size 8192
/* consume a "file-like" object and write bytes to stdout */
static pyobject *py_consume_file(pyobject *self, pyobject *args) {
pyobject *obj;
pyobject *read_meth;
pyobject *result = null;
pyobject *read_args;
if (!pyarg_parsetuple(args,"o", &obj)) {
return null;
}
/* get the read method of the passed object */
if ((read_meth = pyobject_getattrstring(obj, "read")) == null) {
return null;
}
/* build the argument list to read() */
read_args = py_buildvalue("(i)", chunk_size);
while (1) {