简体   繁体   English

Python和.NET之间的二进制文件兼容性

[英]Compatibility of Binary Files between Python and .NET

Can a binary file created by a .NET program be read by Python and vice versa? .NET程序创建的二进制文件可以被Python读取,反之亦然吗?

Which data types would be compatible for this? 哪些数据类型对此兼容?

Example VB.NET program: 示例VB.NET程序:

Sub Main()
    Using writer As New System.IO.BinaryWriter( _
    System.IO.File.Open("Test.bin", IO.FileMode.Create))
        writer.Write(True)
        writer.Write(123)
        writer.Write(123.456)
        writer.Write(987.654D)
        writer.Write("Test string.")
    End Using
    Using reader As New System.IO.BinaryReader( _
    System.IO.File.Open("Test.bin", IO.FileMode.Open))
        Console.WriteLine(reader.ReadBoolean())
        Console.WriteLine(reader.ReadInt32())
        Console.WriteLine(reader.ReadDouble())
        Console.WriteLine(reader.ReadDecimal())
        Console.WriteLine(reader.ReadString())
    End Using
    Console.Write("Press <RETURN> to exit.")
    Console.ReadKey()
End Sub

It's very unlikely that Python uses identical conventions for storing binary data. Python不太可能使用相同的约定来存储二进制数据。

Issues to be aware of include everything from endianess to how data structures are laid out. 需要注意的问题包括从持久性到数据结构布局的所有方面。 Intel CPUs use least-significant bit ordering, the TCP/IP network protocol and many non-Intel CPUs including the CPUs that UNIX traditionally ran on, use most-significant bit ordering. 英特尔CPU使用最低有效位排序,TCP / IP网络协议和许多非英特尔CPU(包括UNIX传统上运行的CPU)使用最高有效位排序。 A platform-agnostic system like .NET will stick with one ordering when it writes binary files. 诸如.NET之类的与平台无关的系统,在写入二进制文件时将遵循一个顺序。 So .NET will be compatible with itself whether it's running on a Core i7 or ARM or some other CPU. 因此,无论.NET是在Core i7还是ARM或其他CPU上运行,它都将与其自身兼容。 But even if Python consistently uses the same ordering as .NET, it's just completely unlikely that it is going to lay out data types and data structures the same way. 但是,即使Python始终使用与.NET相同的顺序,也完全不可能以相同的方式布置数据类型和数据结构。

This leaves you in the position if needing to use a compatible file IO library on both platforms, which is more work than you want to sign up for. 如果需要在两个平台上使用兼容的文件IO库,这将使您处于有利位置,这比您要注册要花更多的工作。

Fortunately, there are libraries available for your use. 幸运的是,有一些库可供您使用。 See this answer for one example. 参见此答案的一个示例。

Of course, the modern friendly way to do this sort of thing is to write out a delimited text file in a format like XML or JSON. 当然,现代的友好方法是用XML或JSON等格式写出带分隔符的文本文件。 Or, if you're dealing with very large data sets, just use a database. 或者,如果您要处理非常大的数据集,则只需使用数据库即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM