【问题标题】:Passing a byte[] array as multiple arguments for a method将 byte[] 数组作为方法的多个参数传递
【发布时间】:2013-11-21 01:22:05
【问题描述】:

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

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

因此,我们的想法是最终将一堆变量串在一起形成同一个字节数组。然后通过 Internet 传递该数组。现在假设所有这些变量都被发送到调用远程函数,如下所示。

//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)
{

}

【问题讨论】:

  • 我不知道你想达到什么目的,但你不能使用套接字和字节缓冲区吗?
  • 您所描述的称为“编组”参数。所有 RPC 库都提供了自动执行此操作的方法。使用其中之一,而不是重新发明轮子。
  • 优秀的信息 Barmar!我会四处寻找一个好的,有什么建议吗?

标签: c++ c methods arguments bytearray


【解决方案1】:

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

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

然后你可以使用 memcopy 和这个结构的参数,参考 -> Send struct over socket in C

【讨论】:

  • 这与我想要完成的非常接近!不过,Barmar 提到的自动“编组”的 RPC 库更接近。感谢您的意见!
【解决方案2】:

好的,正如 Barmar 在 cmets 中所说,我正在尝试完成的工作已经通过 RPC(远程过程调用)编组 完成。他建议找到一个好的库,而不是重新发明轮子。

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

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

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

【讨论】:

    猜你喜欢
    • 2010-10-24
    • 2013-09-12
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2020-10-06
    • 2022-06-29
    相关资源
    最近更新 更多