将 byte[] 数组作为方法的多个参数传递

Passing a byte[] array as multiple arguments for a method

本文关键字:方法 参数传递 byte 数组      更新时间:2023-10-16

考虑以下情况:(伪代码)

//All our luscious data
char theChar = 123;
int theInt = 4324;
char[] theCharArray = "sometext";
//Make an array to hold all of that data.
byte[] allTheVars = new *byte[sizeOfArray];
//Copy all vars into "allTheVars"
copyToEndOfArray(theChar, allTheVars);
copyToEndOfArray(theInt, allTheVars);
copyToEndOfArray(theCharArray, allTheVars);

所以这个想法是你最终得到一堆变量串在一起到同一个字节数组中。然后,此数组通过互联网传递。现在假设所有这些变量都被发送到调用远程函数,如下所示。

//This is the function that will take in the data we sent over the network.
void remotelyCalledInternetFunction(char aChar, int anInt, char[] aCharArray)
{
}

与其通过繁琐地从字节数组复制来手动将每个变量拆分为其指定的类型,不如让方法通过执行这样的事情来"自动拆分"变量吗?

//Pass the byte array. The method knows what types it needs, maybe it will auto-split the data correctly?
remotelyCalledInternetFunction(allTheVars);

如果没有,我能做些什么类似的事情吗?


编辑:有什么方法可以做这样的事情吗?

remotelyCalledInternetFunction(allTheVars);
//Takes first 2 bytes of the array, the next 4 bytes, and the rest for the char[]?
void remotelyCalledInternetFunction(char aChar, int anInt, char[] aCharArray)
{
}

我建议使用结构来存储和传输数据,如下所示。这将自动处理接收函数处的数据拆分。

struct myStruct {
char theChar;
int theInt;
char[] theCharArray;
}

然后,您可以将memcopy与此结构的参数一起使用,请参阅-> 在 C 中通过套接字发送结构。

好的,正如 Barmar 在评论中所说,我试图完成的事情已经通过 RPC(远程过程调用)封送完成。他建议找一个好的图书馆,而不是重新发明轮子。

我发现一个看起来相当不错的库:https://github.com/cinemast/libjson-rpc-cpp

(Jozef 也有一个很好的使用结构的解决方案,谢谢你:D)

编辑:我需要一个低延迟在线游戏的库,所以我最终可能会编写自己的。