Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

python - Writing continious numpy array in raw representation via socket

I need to send big fixed sized buffers from python to c/c++ code side. From python side I have buffers in form of:

array = np.zeros([1000], dtype=np.uint8)
array = fill(array)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 1010))

Code below is used to recv data from connected socket from C/C++ side.From the c/c++ side I need to have this buffer as raw 1000 byte array, I don't need any headers, I need just data. Unfortunately I haven't found howto do it. In general np.tofile()- makes things I need but in file.

int recvBuffer(uint8_t *p_buff, uint32_t size, int socket)
{
    uint32_t recived = 0;
    uint8_t *p_curr = p_buff;
    while (recived < size)
    {
        int ret = recv(tcp_sock, p_curr, size - recived, 0);
        if (ret != -1)
        {
            p_curr += ret;
            recived += ret;
        }
        else
        {
            return false;
        }
    }
    return true;
}

question from:https://stackoverflow.com/questions/65858349/writing-continious-numpy-array-in-raw-representation-via-socket

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found solution. I found it in np.tofile description.

np_array = np.zeros([1000], dtype=np.uint8)
np_array = fill(np_array)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 1010))
raw_buffer = np_array.to_bytes()
s.send(raw_buffer)

Makes exactlty what I wanted. raw_buffer - holds np.array buffer as raw c-stype buffer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...