这样做的现代方式 [英] A modern way of doing this

查看:80
本文介绍了这样做的现代方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我有一个非常古老的c ++程序,它将UDP广播发送到我的本地局域网并将结果返回到一个char数组(this-> buf)



Hi all I have a really old c++ program that sends a UDP broadcast to my local LAN and returns the result in a char array (this->buf)

// Initial discovery broadcast - should return a request string in a char array.
this->Result = recvfrom(this->udpsocket, this->buf, sizeof(this->buf), 0, (sockaddr *)&this->si_other, &this->slen);





完美无缺,但我想知道在c ++中这样做的现代方法是什么?现代我的意思是使用一个容器而不是一个原始数组的字符作为返回值。



It works perfectly but I'm wondering what would be the *modern* way of doing this in c++ ? by modern I mean using a container other than a raw array of chars for the return value.

推荐答案

比C ++ 98更新的C ++标准规定了矢量内存是连续的。

例如请参阅 c ++ - 假设是安全的STL矢量存储总是连续的? - 堆栈溢出 [ ^ ]和 vector - C ++ Reference [ ^ ]。

你可以做这样的事情:
The C++ Standard newer than C++98 states that vector memory is contiguous.
E.g. see c++ - Is it safe to assume that STL vector storage is always contiguous? - Stack Overflow[^] and vector - C++ Reference[^].
You could do something like this:
class MyClass {
private:
    typedef unisnged char Byte;
    enum { MY_MESSAGE_SIZE = 1024 };
    ...
    std::vector<Byte> buffer;
    ...
public:
    // constructor
    MyClass()
    : ...
    , buffer(MY_MESSAGE_SIZE) // IMPORTANT: This allocates a vector of the given size
    , ...
    { ... }
    
    void doSomethingUseful(...) {
        ...
        result = recvfrom(udpsocket, &(buffer[0]), MY_MESSAGE_SIZE, 0, (sockaddr *)&si_other, &slen);
        ...
    }
};

干杯

Andi

Cheers
Andi


你为什么要改变有用的东西? UDP套接字调用相对简单,保持这种方式...



如果有的话,我会确保调用是异步的,并给它一个超时时间以防万一你永远不会得到回复(否则,你只是有一个可以挂起你的程序的电话)。
Why would you change something that works? UDP socket calls are relatively simple, keep it that way...

If anything, I'd make sure that call was asynchronous and give it a timeout period in case you never get a response (otherwise, you just have a call that can hang your program).


这篇关于这样做的现代方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆