我需要在Python在.NET組件(經由pythonnet's clr
module訪問打開一個可寫的文件句柄,然後手離開文件描述符的功能。如何從Python文件句柄打開.NET FileStream對象?
從Python文件對象獲取到的win32 HANDLE*
是相當簡單的,如圖this question:
import clr
from Microsoft.Win32.SafeHandles import SafeFileHandle
from System.IO import FileStream, FileAccess
pyf=open("c:/temp/testing123.txt","w")
fileno=pyf.fileno()
print fileno # 6
handle = msvcrt.get_osfhandle(fileno)
print handle # 1832L
According to MSDN,應該現在是可能的,無論是從直IntPtr
(把手)構建標準FileStream
對象或從SafeFileHandle
包裝
FileStream(IntPtr, FileAccess)
FileStream(SafeFileHandle, FileAccess)
問題是...我怎麼能說服clr
模塊投handle
作爲IntPtr
?
我已經試過以下的各種版本,但他們都給予我的錯誤:
FileStream(IntPtr(handle), True)
FileStream(IntPtr(Int64(handle), True)
FileStream(IntPtr(Int32(handle), True)
SafeFileHandle(IntPtr(handle), True)
...
=> TypeError ("value cannot be converted to System.IntPtr")
如何得到這個該死的文件句柄到C#有什麼建議?
這個怎麼樣? http://stackoverflow.com/a/14334609/2230844 – denfromufa
否則爲什麼不使用COM,如果這是Win32? – denfromufa
@denfromufa,由於各種原因,CLR API對於這個項目來說是優越的。您鏈接的答案解釋瞭如何從C++獲取託管句柄到C#中,但不幸的是,這對Python的情況並沒有幫助。 –