c++ - 将 int 转换为 void *data 并获取以字节为单位的长度

标签 c++ sockets sdl sdl-net

我正在尝试使用 SDLNet_TCP_Send(TCPsocket sock, void *data, int len) 函数(SDL_net 库的一部分),我很难弄清楚如何使用它发送一个 int。我可以这样做还是应该使用其他方法?

最佳答案

"how I could use this to send an int ... Would I be able to do that or should I use another approach?"

该函数可用于执行此操作。您只需使用一个地址和 sizeof():

int dataToSend = 42;
SDLNet_TCP_Send(sock, &dataToSend, sizeof(dataToSend)); 

根据数据协议(protocol),您可能需要遵守整数数据应以网络字节顺序发送(使其与机器架构无关):

#include <arpa/inet.h>

int dataToSend = htonl(42);
              // ^^^^^ Make integer network byte ordered (big endian)
SDLNet_TCP_Send(sock, &dataToSend, sizeof(dataToSend)); 

关于c++ - 将 int 转换为 void *data 并获取以字节为单位的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656546/

相关文章:

c++ - 为什么要使用 const 进行隐式转换?

c++ - 您如何使用字符覆盖在 Windows 上进行屏蔽密码输入?

java - 当接收者没有它的类时通过套接字发送对象

java套接字和DoS

c++ - SDL_PollEvent 未拾取所有事件

c++ - 理解SDL帧动画

c++ - Qt 未定义对 `vtable for Msnger' 的引用

c++ - 我是否必须检查此方法的指针有效性?

c - 代理需要非阻塞套接字吗?

c++ - SDL 2 无法打开 Controller ,但可以识别操纵杆