Making FreeBASIC and VB.NET Work Together with Binary Files

By vdecampo

Part I: Alignment and Field Offsets

I have been working on a project that had two portions, one written in FreeBASIC, and the other in VB.NET. During the project it became necessary to have binary files that could be shared by both languages. My initial attempts failed but I finally found a method that worked well. In this tutorial I will attempt to explain how you can make binary files that both languages can access.

FreeBASIC Type

In FreeBASIC, structures are defined using the TYPE declaration. Here is a code sample…

Type _mytype
     As Byte    flag
     As Integer x,y,z
End Type 


When this structure is written to disk you might assume it will be 13 bytes long (3 Integers + 1 Byte = 13 bytes) but FreeBASIC will pad the flag field with 3 extra bytes to align the next field on an Integer boundary. To get the structure to write to disk exactly as is you need to specify a padding alignment of 1. You do this by adding the FIELD directive.

Type _mytype Field = 1
     As Byte    flag
     As Integer x,y,z     
End Type 


The structure will now write to disk as it appears. Now let’s take a look at the corresponding structure in VB.NET. In VB.NET, the TYPE directive is now called STRUCTURE. To avoid the same padding and alignment issues that we had in FreeBASIC, VB.NET offers similar directives that can be specified when defining the structure.

VB.NET Structure

Structure _mytype
           Dim Flag As Byte
           Dim x,y,z as Integer      
End Structure   


There are several directives going on here but the three things I want to point out here are ‘Pack:=1’ and ‘Size:=13’ and ‘FieldOffset(x)’. Pack tells VB to not pad fields with extra bytes. Size tells VB exactly how large the structure will be, and FieldOffset(x) tells VB the exact starting byte position for each field. Using this method you can create binary files that are readable by both languages.

Next Tutorial: Passing fixed length strings

Powered by CMSimple | CMSimple Legal Notices | (X)html | css | Login | Template-Design: Lars Ellmauer | Template-Modified: Imortisoft ISD