c++| problem in recent days to see the csdn to ask C + + and Java communication problems are more, especially the C-specific data structures (such as struct).
Specially according to a netizen's question to give an example, hoped has the help to the beginner.
See the original question: http://community.csdn.net/Expert/topic/3886/3886989.xml?temp=.3527033
This type of problem is usually caused by an existing server or a server that cannot be modified (typically C + +).
For example, the server end receives only one structure employee, as defined below:
struct UserInfo {
Char username[20];
int UserId;
};
struct Employee {
UserInfo user;
float salary;
};
Of course, it can also be defined as
struct Employee {
Char name[20];
int id;
float salary;
};
Java Client test source (to illustrate the problem, assuming struct byte alignment, sizeof (Employee) =28)
Import java.net.*;
/**
* Communicate with C language (Java do client,c/c++ do server, send a structure)
* @author Kingfish
* @version 1.0
*/
Class Employee {
Private byte[] buf = new BYTE[28]; To illustrate the problem, set the dead size, the event can be flexibly handled
/**
* Convert int to low byte before, byte array after high byte
*/
private static byte[] Tolh (int n) {
Byte[] B = new Byte[4];
B[0] = (byte) (n & 0xff);
B[1] = (byte) (n >> 8 & 0xff);
B[2] = (byte) (n >> & 0xff);
B[3] = (byte) (n >> & 0xff);
return b;
}
/**
* Convert float to low byte before, byte array after high byte
*/
private static byte[] Tolh (float f) {
Return Tolh (Float.floattorawintbits (f));
}
/**
* Construct and convert
*/
Public Employee (String name, int id, float salary) {
byte[] temp = name.getbytes ();
System.arraycopy (temp, 0, buf, 0, temp.length);
Of course, you can also use the Writeint,writefloat method to send, but the byte order needs to be lower than before.
This question is being discussed later.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.