简体   繁体   English

python中memcpy的替代方法是什么?

[英]What is the alternative of memcpy in python?

I have a class object in python. 我在python中有一个类对象。 I want to send that object values through TCP. 我想通过TCP发送该对象值。

I know if it is C++ I can send it like following.. 我知道是否是C ++,可以像下面这样发送。

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. 现在我必须在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. 它不等同于C memcpy ,但是如果您的要求是通过TCP发送对象并在另一端进行重构,则pickle模块适合您。

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 : 编辑:来自Python 3.4 的Python标准库手册中的示例:

For the simplest code, use the dump() and load() functions. 对于最简单的代码,请使用dump()和load()函数。

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. struct软件包可以为您完成此任务。

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). 您必须指定字符串的最大长度(此处为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. 您的C ++版本不起作用,因为字符串的原始字节将包含指针而不是字符串中的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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