10

I'm sure this is documented somewhere but i can't find it...

My code is getting a python object from another library (that i can't modify), and i need to call some win32 api functions on it.

Python returns something that isn't the os-level handle from file.fileno(), my guess is that it gives MSVCRT's fileno.

>>> ctypes.windll.kernel32.CreateFileA('test',0x80000000L,1,None,3,0,0)
1948 # <- HANDLE

>>> file('test','r').fileno()
4 # <- not a HANDLE

How do i convert it into a real win32 handle?

bdew
  • 1,330
  • 9
  • 22
  • This seems like a hackish approach to do things. I suggest using the CreateFile approach as you have full control on what parameters are passed to CreateFile, and its generally the right way to get a handle. You can do it with win32file aswell (instead of ctypes). – Grim May 26 '11 at 08:43
  • It might be hackish, but i can't do CreateFile() myself because i get a python file object from code not under my control. – bdew May 26 '11 at 08:50

2 Answers2

12

I found the answer:

>>> msvcrt.get_osfhandle(a.fileno())
1956 # valid HANDLE

This is actually documented on http://docs.python.org/library/msvcrt.html , no idea how i missed it.

bdew
  • 1,330
  • 9
  • 22
4

win32file._get_osfhandle from the PyWin32 library will return what you want. win32file._get_osfhandle(a.fileno()) returns the same thing as msvcrt.get_osfhandle(a.fileno()) in my testing.

Gabe
  • 84,912
  • 12
  • 139
  • 238