简体   繁体   中英

What is the alternative of memcpy in python?

I have a class object in python. I want to send that object values through TCP.

I know if it is C++ I can send it like following..

class Abc
{
    int x;
    float y;
    string x;
};

Abc Obj;
char* data = new char[sizeof(Abc)];
memcpy(data, &obj, sizeof(Abc));
tcpsender.send(data);    // may be incorrect syntax

Thus the data will be sent to destination as bytes.

now i have to do this in Python.

what is the alternative part of these two lines.

/*
char* data = new char[sizeof(Abc)];
memcpy(data, &obj, sizeof(Abc));
*/

It is not the equivalent of C memcpy , but if your requirement is to send an object through TCP and reconstruct if at the other side, pickle module is for you.

Is is targetted as storing objects in sequential files or strings and retrieving them, including across different architectures.

Edit : example from The Python Standard Library manual for Python 3.4 :

For the simplest code, use the dump() and load() functions.

import pickle

# An arbitrary collection of objects supported by pickle.
data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': set([None, True, False])
}

with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

The following example reads the resulting pickled data.

import pickle

with open('data.pickle', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)

The struct package can do this for you.

import struct

fmt = 'if10p'
data = struct.pack(fmt, 42, 1.234, 'hello')
print struct.unpack(fmt, data)

You have to specify the maximum length of the string (here 10). Your C++ version doesn't work because the raw bytes of a string will contain a pointer rather than the characters inside the sting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM