Android Question user-defined types - conversion to array of primitive bytes

brucePERU

New Member
Licensed User
Longtime User
Hello

I want to send packets TCP to a server in lazarus (object pascal) from types defined in B4A. The idea is to convert it to primitive byte array
B4X:
Type  TPackPosition(Hour As long, latitude As Double, longitude As double)
...
..
Dim Position as TPackPosition
Position.initialize
Position.Hour = DateTime.now
Position.Latitude = -16.46541
Position.Latitude = -70.487899

Dim obj As Object = Position
Dim buffer() as byte = obj
...
Stream.Write(buffer)


Please I need your great support,

Bruce
 

DonManfred

Expert
Licensed User
Longtime User
As far as i know there is no Pascal/Delphi implementation.

But using B4A/J/I you can use B4XSerializator. Here it is easy

B4X:
    Dim Position As TPackPosition
    Position.initialize
    Position.Hour = DateTime.now
    Position.Latitude = -16.46541
    Position.Latitude = -70.487899
    Dim ser As B4XSerializator ' RandomAccessFile library
    ser.ConvertObjectToBytesAsync(Position,"PosType")
    wait for PosType_ObjectToBytes (Success As Boolean, Bytes() As Byte)
    Log($"PosType_ObjectToBytes(${Success},${Bytes.Length})"$)
    Dim ser As B4XSerializator
    ser.ConvertBytesToObject(Bytes)
    wait for PosType_BytesToObject (Success As Boolean, NewObject As Object)
    Log($"PosType_BytesToObject(${Success}, ${NewObject})"$)

You can use RandomAccessfile to convert the Type to bytes.

B4X:
    Dim raf As RandomAccessFile
    raf.Initialize(File.DirInternal,"1.dat",False)
    raf.WriteB4XObject(Position,0)
    raf.Close

    Dim bytes() As Byte = File.ReadBytes(File.DirInternal,"1.dat")
 
Upvote 0

brucePERU

New Member
Licensed User
Longtime User
Hi DonManfred

B4X:
Dim Position As TPackPosition
    Position.initialize
    Position.Hour = DateTime.now
    Position.Latitude = -16.46541
    Position.Latitude = -70.487899
    Dim ser As B4XSerializator ' RandomAccessFile library
    ser.ConvertObjectToBytesAsync(Position,"PosType")
    wait for PosType_ObjectToBytes (Success As Boolean, Bytes() As Byte)
    Log($"PosType_ObjectToBytes(${Success},${Bytes.Length})"$)

which means the content of the variable "bytes"
 

Attachments

  • capt1.png
    17.2 KB · Views: 226
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…