Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Python pickle bytes object in C#

Tags:

c#

python.net

Using Pythonnet in a C# application:

Python returns a bytes ({<class 'bytes'>}) object which is the result of a pickle.dumps operation.

What is the best way of dealing with this object in C# in terms of persistance to blob storage and rehydrating a bytes object to pass back to Python at a later stage?

like image 607
cillierscharl Avatar asked Mar 05 '19 16:03

cillierscharl


People also ask

Can you pickle an object Python?

Python comes with a built-in package, known as pickle , that can be used to perform pickling and unpickling operations. Pickling and unpickling in Python is the process that is used to describe the conversion of objects into byte streams and vice versa - serialization and deserialization, using Python's pickle module.

How do I Unpickle a pickle file?

As we said earlier, the load() method can be used to unpickle the pickled Python object. You have to first open the pickled file using rb (read-binary) permission and pass the opened file to the load() method, as shown below. The load() method unpickles the data and returns the actual object.

How do you load a pickle object?

Python Pickle load You have to use pickle. load() function to do that. The primary argument of pickle load function is the file object that you get by opening the file in read-binary (rb) mode. Simple!

Can pickle store class objects in Python?

The pickle module can store things such as data types such as booleans, strings, and byte arrays, lists, dictionaries, functions, and more.


1 Answers

Assuming you have access to the Python side of the equation, the easiest way to deal with these sorts of problem is to serialize the object in some sort of mutually understood format.

In this case, one idea would be to serialize the bytes into base64 (unicode such as UTF-8 or -16 can run into encoding issues depending on the contents of the byte string). Then you could convert that base64 bytes into UTF-8 to communicate it back across programs.

This looks like (for example):

base64.b64encode(pickle.dumps("Some data goes here")).decode("utf-8")
like image 173
Eric Le Fort Avatar answered Oct 10 '22 20:10

Eric Le Fort