我有一个 Java 程序,它将(通过 TCP)发送数据包到 C++ 程序。只会发送两种类型的对象(结构 A 或结构 B)。我需要序列化这两个对象并将它们发送到 c++ 程序,这样当在 c++ 程序中反序列化时,它们将是 struct A 或 struct B 类型,具体取决于已发送的内容。我如何在没有任何外部 java 包的情况下实现这一目标?
struct A
{
unsigned int field1;
unsigned int field2;
}
struct B
{
unsigned int length;
struct A list[GLOBALLENGTH];
}
Run Code Online (Sandbox Code Playgroud)
GLOBALLENGTH 是一个静态的全局整数。
请注意,我不需要通用解决方案,因为我将严格处理上述类型。另外,我无法访问 C++ 程序(它是一个黑匣子),两者都以小印度语运行。
听起来像 c++ 程序期望每个结构中的数据的原始转储,没有填充,按小端顺序,字段按声明的顺序,使用 32 位整数。如果一切顺利,这里有一种写入字节供 c++ 程序使用的方法:
private static final int A_SIZE = 8;
private static final int B_SIZE = 4 + GLOBALLENGTH * 8;
public byte[] writeA(A a) {
byte[] bytes = new byte[A_SIZE];
writeA(a, bytes, 0);
return bytes;
}
private void writeA(A a, byte[] bytes, int offset) {
ByteBuffer buff = ByteBuffer.wrap(bytes, offset, A_SIZE);
buff.order(ByteOrder.LITTLE_ENDIAN);
buff.putInt(a.field1).putInt(a.field2);
}
public byte[] writeB(B b) {
byte[] bytes = new byte[B_SIZE];
ByteBuffer buff = ByteBuffer.wrap(bytes, 0, 4);
buff.order(ByteOrder.LITTLE_ENDIAN);
buff.putInt(b.length);
int offset = 4;
for (A a : b.list) {
writeA(a, bytes, offset);
offset += A_SIZE;
}
return bytes;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以调用适当的公共方法(writeA(A)或writeB(B))并将字节发送到服务器。
| 归档时间: |
|
| 查看次数: |
4151 次 |
| 最近记录: |