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

时间:2022-03-19 18:16:09

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. Would I be able to do that or should I use another approach?

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

2 个解决方案

#1


4  

"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)); 

#2


2  

Given int x; you should be able to trivially call the function like this:

给定int x;你应该能够像这样简单地调用函数:

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

#1


4  

"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)); 

#2


2  

Given int x; you should be able to trivially call the function like this:

给定int x;你应该能够像这样简单地调用函数:

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