2

我想使用 ctypes 包从 64 位 python 调用 msvcrt 函数。我显然做错了。正确的做法是显而易见的吗?

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> libc = ctypes.cdll.msvcrt
>>> fp = libc.fopen('text.txt', 'wb') #Seems to work, creates a file
>>> libc.fclose(ctypes.c_void_p(fp))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
WindowsError: exception: access violation reading 0xFFFFFFFFFF082B28
>>>

如果这段代码符合我的要求,它会打开和关闭一个文本文件而不会崩溃。

4

1 回答 1

6

默认的 ctypes 结果类型是 32 位整数,但文件句柄是指针宽度,即 64 位。因此,您丢失了文件指针中的一半信息。

在调用 fopen 之前,您必须声明结果类型是指针:

libc.fopen.restype = ctypes.c_void_p
fp = libc.fopen(...)
libc.fclose(fp)
于 2011-10-25T22:56:14.373 回答