Andrew
Andrew

Reputation: 2892

Using msvcrt in 64-bit python ctypes

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.

Upvotes: 2

Views: 1632

Answers (1)

David Heffernan
David Heffernan

Reputation: 613053

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)

Upvotes: 6

Related Questions