How to rewrite this to GDScript?

Godot Version



I have this function in Python:

def create_packet(code, data):
    # Adding packet code and data length
    packet_code = struct.pack('!I', code)
    data_length = struct.pack('!I', len(data))
    # Full packet
    return b'1337' + packet_code + data_length + data

And i’ve tried to rewrite it to GDScript:

func create_packet(id: int, data: String) -> PackedByteArray:
	var packet: PackedByteArray
	var data1 = var_to_bytes(data)
	return packet

But it not works. My server log and comparison between python client and godot:

[SERVER] Started at localhost:1337
[SERVER] Connection! ('', 36038)
[SERVER] Created player PythonClient
[->PythonClient] ServerKeepAlive
From PythonClient: 10000
[PythonClient] ClientKeepAlive
From PythonClient: 1337'1
code and data length: 10005 1
[PythonClient] Received packet 10005
[PythonClient] ClientCreateRoom
[->PythonClient] Created room with id RNFB6
From PythonClient: 10000
[PythonClient] ClientKeepAlive
[SERVER] Connection! ('', 45332)
[SERVER] Created player GodotClient
[->GodotClient] ServerKeepAlive
From GodotClient: 10000
[GodotClient] ClientKeepAlive
From GodotClient: 1337
code and data length: 353108992 256
[SERVER] Error with GodotClient | There is not enough data in the packet
[GodotClient] dissconected!

What i doing wrong?

Might need to use packet.encode_s32()? I am not sure what size the python b string makes it’s integer types but godot is pretty explicit when encoding. Another bummer to note from godot’s PackedByteArray docs:

PackedByteArray also provides methods to encode/decode various types to/from bytes. The way values are encoded is an implementation detail and shouldn’t be relied upon when interacting with external apps.

You make have to dig through the engine’s source code for your specific version to understand it.