Serialize and deserialize geometry [Python] - ByteArrayToCommonObject return True [SOLVED]

I’m trying to serialize and deserialize geometry by using CommonObjectToByteArray and ByteArrayToCommonObject

But when recreating the object with ByteArrayToCommonObject it only returns True, while it should return an instance of an object?
Anyone who can point me in what I’m doing wrong here?

Grateful for some help!

import base64
import Grasshopper as gh
import Rhino.Geometry as rg

byte_arr = str(gh.Kernel.GH_Convert.CommonObjectToByteArray(obj))
a = base64.b64encode(byte_arr)

byte_arr = bytearray(base64.b64decode(a))
obj = gh.Kernel.GH_Convert.ByteArrayToCommonObject<rg.Brep>(byte_arr)

help (6.6 KB)

Hi Andre,

I like to be more pure and always do it the raw C# way. And I am sorry I did not provide a python solution, but I am sure you can translate this short piece of code

// Include these namespaces
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

 private void RunScript(Brep x, ref object A)

    byte [] content = Serialize(x);
    Brep b = Deserialize<Brep>(content);

    A = b;



   byte[] Serialize(object obj)
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
      bf.Serialize(ms, obj);
      return ms.ToArray();

// T just means the method is Generic. The type to deserialize to has to be known at compile time
  T Deserialize<T>(byte[] data)
    using (MemoryStream ms = new MemoryStream(data))
      BinaryFormatter bf = new BinaryFormatter();
      return (T)bf.Deserialize(ms);

My preferred way of doing this though, is just to save the data to a binary file and then read from it. It offers a broader access to the data from any programming context.


hey @agi.andre,

Just in case, I’ve translated that to python for you: (8.1 KB)

I’d suggest to take a look at the pickle module for serialization in python as well.




Thank you so much @rawitscher-torres and @DavidLeon !
This works like a charm now :smiley:
Interesting to see the use of System.Runtime. This solution is much more robust since it is not dependent on type of geometry. Now I don’t have to declare if it’s strings or, breps, points…etc.

Thank you for the help!