将 byte[] 数组作为方法的多个参数传递
Passing a byte[] array as multiple arguments for a method
考虑以下情况:(伪代码)
//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)
编辑:我需要一个低延迟在线游戏的库,所以我最终可能会编写自己的。
相关文章:
- 将成员函数指针作为参数传递给模板方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何在方法中传递结构参数
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 将带有模板化方法的类作为带有GCC的模板参数传递
- 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 如何将提升回调作为参数传递给方法?
- 将方法作为模板化参数传递 C++11
- 最佳做法是在方法中传递参数
- 将 std::ofstream 对象作为参数传递给类方法
- 在构造函数上传递参数或在每个方法上传递参数
- 将给定的 vararg 参数传递给另一个函数的适当方法是什么?
- 将指针类方法作为参数传递给其他类方法C
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- JNI——可以将复杂类型作为本机方法参数传递
- OOP 设计 - 将类成员变量作为类中的方法参数传递
- C++将动态方法指针作为不同类的方法参数传递
- 如何将指向一个方法的指针作为另一个方法参数传递
- 将内联双数组作为方法参数传递