简体   繁体   English

将int转换为void * data并获取长度(以字节为单位)

[英]Converting an int to void *data and getting the length in bytes

I am trying to use the SDLNet_TCP_Send(TCPsocket sock, void *data, int len) function (part of the SDL_net library) and I am having a hard time figuring out how I could use this to send an int . 我正在尝试使用SDLNet_TCP_Send(TCPsocket sock, void *data, int len)函数(SDL_net库的一部分),并且很难弄清楚如何使用它来发送int Would I be able to do that or should I use another approach? 我能够做到这一点还是应该使用其他方法?

"how I could use this to send an int ... Would I be able to do that or should I use another approach?" “我该如何使用它发送一个int信息?我能够做到这一点还是应该使用其他方法?”

The function can be used to do so. 该功能可用于执行此操作。 You just use an address and sizeof() : 您只需要使用一个地址和sizeof()

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

Depending on the data protocol you might need to obey that integer data should be sent in network byte order (to have it machine architecture independend): 根据数据协议,您可能需要遵守整数数据应按网络字节顺序发送(以使其独立于机器体系结构):

#include <arpa/inet.h>

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

Given int x; 给定int x; you should be able to trivially call the function like this: 您应该能够像这样简单地调用该函数:

SDLNet_TCP_Send(socket, &x, sizeof(x));

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

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