Python 3替代PyFile_AsFile [英] Python 3 replacement for PyFile_AsFile

查看:86
本文介绍了Python 3替代PyFile_AsFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在Python 2中有效:

The following code works in Python 2:

from ctypes import *

## Setup python file -> c 'FILE *' conversion :
class FILE(Structure):
    pass
FILE_P = POINTER(FILE)
PyFile_AsFile = pythonapi.PyFile_AsFile # problem here
PyFile_AsFile.argtypes = [py_object]
PyFile_AsFile.restype = FILE_P
fp = open(filename,'wb')
gd.gdImagePng(img, PyFile_AsFile(fp))

但是在Python 3中,pythonapi中没有PyFile_AsFile。

But in Python 3, there is no PyFile_AsFile in pythonapi.

代码是 testPixelOps.py 的例外。

推荐答案


我只需要一种将文件对象转换为ctypes FILE *的方法,以便将其传递给GD。

I just needed a way to convert a file object to a ctypes FILE* so that I can pass it to GD.

您不走运。这在Python 2.x中是可能的,但在Python 3.x中是不可能的。 文档说明了为什么不这样做:

You are out of luck. That was possible in Python 2.x, but is not possible in Python 3.x. The documentation explains why not:


这些API是用于内置文件对象的Python 2 C API的最小模拟,该文件过去依赖于C标准库中的缓冲I / O(FILE *)支持。在Python 3中,文件和流使用新的io模块,该模块在操作系统的低级无缓冲I / O上定义了几层。

These APIs are a minimal emulation of the Python 2 C API for built-in file objects, which used to rely on the buffered I/O (FILE*) support from the C standard library. In Python 3, files and streams use the new io module, which defines several layers over the low-level unbuffered I/O of the operating system.

如果需要 FILE * ,则必须直接使用C标准库来自己制作。

If you want a FILE* you are going to have to make one yourself, using the C standard library directly.

这篇关于Python 3替代PyFile_AsFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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