如何从Python文件句柄打开.NET FileStream对象? [英] How can I open a .NET FileStream object from a Python file handle?

查看:232
本文介绍了如何从Python文件句柄打开.NET FileStream对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Python中打开可写文件句柄,然后将文件描述符传递给.NET程序集中的函数(通过

I need to open a writable file handle in Python and then hand off the file descriptor to a function in a .NET assembly (accessed via pythonnet's clr module.

从Python文件对象到win32 HANDLE*相当简单,如

Getting from the Python file object to the win32 HANDLE* is fairly straightforward, as shown in 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

根据MSDN ,现在应该可以从直线IntPtr(手柄)或SafeFileHandle包装器构造标准的FileStream对象.

According to MSDN, it should now be possible to construct a standard FileStream object from either a straight IntPtr (the handle) or from a SafeFileHandle wrapper.

FileStream(IntPtr, FileAccess)
FileStream(SafeFileHandle, FileAccess)

问题是...我如何说服clr模块将handle转换为IntPtr?

The problem is... how can I convince the clr module to cast handle as an IntPtr?

我尝试了以下各种版本,但它们都给我错误:

I've tried various versions of the following, but they all give me errors:

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

关于如何将该Darn文件句柄导入C#的任何建议?

Any suggestions for how to get this darn file handle into C#?

推荐答案

感谢 pythonnet邮件列表.

Got an answer thanks to the good folks on the pythonnet mailing list.

关键是使用Overloads构造函数将win32 HANDLE强制转换为IntPtr类型.

The key is to use the Overloads constructor to force-cast the win32 HANDLE to IntPtr type.

这是一个完整的工作示例:

Here's a complete working example:

import tempfile, msvcrt
import clr, msvcrt
from System.IO import FileStream, FileAccess
from System import IntPtr

with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as pyf:
    fileno=pyf.fileno()
    print "fileno", fileno
    handle = msvcrt.get_osfhandle(fileno)
    print "HANDLE", handle

    pyf.write("Python\n")
    pyf.flush()

    cs_handle = IntPtr.Overloads[long](handle)
    cs_fs = FileStream(cs_handle, FileAccess.Write)
    cs_fs.Write("CLR\n", 0, 4)
    cs_fs.Flush()

print "file should contain a line from Python and a line from CLR: ", pyf.name

这篇关于如何从Python文件句柄打开.NET FileStream对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆