Click here to Skip to main content
12,818,315 members (33,568 online)
Click here to Skip to main content
Add your own
alternative version


8 bookmarked
Posted 23 Mar 2008

Object Reader and Writer

, 23 Mar 2008 LGPL3
Rate this:
Please Sign up or sign in to vote.
Reads/Writes an object from/to a stream


Some days ago, I was writing a program that needed to parse a truetype font. I found that there is no class to fill a structure from a stream. So I wrote one myself.

Using the Code

Basically, if you only want to read/write a structure with the following conditions...

  1. All data is stored in fields
  2. All data is primitive type

... it will be very easy, like this:

'reader can be BinaryReader or Stream
result = ObjectReader(Of SomeStruct).Read(reader)
'writer can be BinaryWriter or Stream
ObjectWriter(Of SomeStruct).Write(obj, writer) 

Arrays and non-primitive types can also be read/written, but you need to add some attribute to the field. Here is an example:

    (Runtime.InteropServices.LayoutKind.Sequential)> _
Public Structure TestStruct
    Public aInt As Integer
    Public bInt64 As Long
    <ArraySize(16)> _
    Public bArr As Byte()
    <ArraySize(4)> _
    Public dIArr As Integer()
    <ObjectReaderWriterInclude()> _
    Public eNested As TestStruct3
    Public fNotInclude As TestStruct2 ' this field will not be read/written
    <ObjectReaderWriterInclude()> _
    Public gNested2 As TestStruct2
    <ArraySize(2), ObjectReaderWriterInclude()> _
    Public hNestedArray As TestStruct2()
End Structure

    (Runtime.InteropServices.LayoutKind.Sequential)> _
Public Structure TestStruct2
    Public aB As Byte
    <ArraySize(10)> _
    Public bBArr As Byte()
End Structure

    (Runtime.InteropServices.LayoutKind.Sequential)> _
Public Class TestStruct3
    Public aInt As Integer
    <ObjectReaderWriterInclude()> _
    Public bNested As TestStruct2
End Class


  • 2008-03-24: Initial post


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


About the Author

China China
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 1 Pin
Dave Kreskowiak22-Oct-09 20:06
mvpDave Kreskowiak22-Oct-09 20:06 
GeneralTesting Pin
Stevepsi27-Mar-08 8:06
memberStevepsi27-Mar-08 8:06 
GeneralRe: Testing Pin
SAPikachu1-Apr-08 18:25
memberSAPikachu1-Apr-08 18:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 23 Mar 2008
Article Copyright 2008 by SAPikachu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid