1

I am trying to send python array between python program and Unity3D. Here is the python part to send a string message:

#send the message

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5065

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

msg = "Hello word!"

sock.sendto(msg, (UDP_IP, UDP_PORT))


#receive the message in Unity (C-sharp)

IPEndPoint anyIP = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port);

byte[] data = client.Receive(ref anyIP); 

string text = Encoding.UTF8.GetString(data);

I know that I can transform the numpy array to a string format and parse it to float in Unity. Is there any other elegant way to send and receive a numpy array instead of string?

1 Answer 1

1

Since numpy's ndarray is a binary construct, you need a way to serialize it in Python, and de-serialize in C#.

For serialization, you can use ndarray.tobytes(). To de-serialize, you must pay attention to the data type (double, int, etc.), and the machine's Endianess (little or big).

Also, if you are passing high-dimensional arrays, note the 'C' vs 'Fortran' capabilities of ndarray.tobytes().

For example, in C#, you can deserialize an array of bytes to an array of doubles using Buffer.BlockCopy(), see, for example, this question.

Disclaimer: I haven't tried the above method myself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.