如何使用java传入给c服务端结构体

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012400305/article/details/78317031


在java和C的socket交互中 是用的是结构体传输   java怎么传  其实很简单  c中并没有Java的对象  他的结构体 你只要按照c中结构体的字段 转成字节数组就好了  

比如 

public byte[] MsgToBuf (MsgHead msgHead){
    	 byte[] buf = new byte[20];
    	 int msgh = msgHead.getMsgh();
    	 int msgid = msgHead.getMsgid();
    	 int cmd = msgHead.getCmd();
    	 int error = msgHead.getError();
    	 int dataL = msgHead.getDataL();
    			byte[] temp = clientUtils.intToByteArray(msgh);
//    			byte[] temp = clientUtils.tolh(msgh);
    			System.arraycopy(temp, 0, buf, 0, temp.length);

    			temp = clientUtils.intToByteArray(msgid);
//    			temp = clientUtils.tolh(msgid);
    			System.arraycopy(temp, 0, buf, 4, temp.length);

    			temp = clientUtils.intToByteArray(cmd);
//    			temp = clientUtils.tolh(cmd);
    			System.arraycopy(temp, 0, buf, 8, temp.length);
    			
    			temp = clientUtils.intToByteArray(error);
//    			temp = clientUtils.tolh(error);
    			System.arraycopy(temp, 0, buf, 12, temp.length);
    			
    			temp = clientUtils.intToByteArray(dataL);
//    			temp = clientUtils.tolh(dataL);
    			System.arraycopy(temp, 0, buf, 16, temp.length);
    			
    			return buf;
    }


他是直接开辟字节数组的大小 直接放到数组中就可以的  int转byte的方法 我在其他的博客中有写到     string直接转byte传就好了  

猜你喜欢

转载自blog.csdn.net/u012400305/article/details/78317031
今日推荐