在 64 位 python ctypes 中使用 msvcrt

发布于 2024-12-12 11:03:02 字数 646 浏览 3 评论 0原文

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

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

I want to call msvcrt functions from 64-bit python using the ctypes package. I'm obviously doing it wrong. Is the right way to do it obvious?

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
>>>

If this code did what I want, it would have opened and closed a text file without crashing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

携余温的黄昏 2024-12-19 11:03:02

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

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

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

The default ctypes result type is a 32 bit integer but a file handle is pointer width, i.e. 64 bits. You are therefore losing half of the information in the file pointer.

Before you call fopen you must state that the result type is a pointer:

libc.fopen.restype = ctypes.c_void_p
fp = libc.fopen(...)
libc.fclose(fp)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文