【问题标题】:Using msvcrt in 64-bit python ctypes在 64 位 python ctypes 中使用 msvcrt
【发布时间】:2011-10-25 22:45:22
【问题描述】:

我想使用 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
>>>

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

【问题讨论】:

    标签: python 64-bit ctypes msvcrt


    【解决方案1】:

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

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

    libc.fopen.restype = ctypes.c_void_p
    fp = libc.fopen(...)
    libc.fclose(fp)
    

    【讨论】:

    • 不错!谢谢!这确实是问题所在。
    猜你喜欢
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    相关资源
    最近更新 更多