In recent days, I have seen many questions about communication between C/C ++ and Java on csdn, especially the data structures (such as struct) Unique to C ).
I would like to give an example based on a netizen's question, hoping to help beginners.
Original problem see: http://community.csdn.net/Expert/topic/3886/3886989.xml? Temp =. 3527033.
This type of problem is usually caused by the inability to modify the original server or server (usually C/C ++.
For example, the server receives only one structure employee, which is defined as follows:
Struct userinfo {
Char username [20];
Int userid;
};
Struct employee {
Userinfo user;
Float salary;
};
Of course, it can also be defined
Struct employee {
Char name [20];
Int ID;
Float salary;
};
Java client test source code (for illustration, assuming struct byte alignment, sizeof (employee) = 28)
Import java.net .*;
/**
* Communication with C language (Java serves as the client, C/C ++ serves as the server, and transmits a structure)
* @ Author Kingfish
* @ Version 1.0
*/
Class employee {
Private byte [] Buf = new byte [28]; // determines the size of the problem and flexibly handles the event.
/**
* Convert the int type to the byte array after the low byte type and the high byte type.
*/
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> 16 & 0xff );
B [3] = (byte) (N> 24 & 0xff );
Return B;
}
/**
* Convert float to the byte array with the front and back of the low 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 );
Temp = tolh (ID );
System. arraycopy (temp, 0, Buf, 20, temp. Length );
Temp = tolh (salary );
System. arraycopy (temp, 0, Buf, 24, temp. Length );
}
/**
* Returns the array to be sent.
*/
Public byte [] getbuf (){
Return Buf;
}
/**
* Send Test
*/
Public static void main (string [] ARGs ){
Try {
Socket sock = new socket ("127.0.0.1", 8888 );
Sock. getoutputstream (). Write (new employee ("Kingfish", 123456789,888 8.99f ).
Getbuf ());
Sock. Close ();
}
Catch (exception e ){
E. printstacktrace ();
}
} // End
---------------------------------------------------------------------------
Of course, the writeint and writefloat methods can also be used for sending, but the byte order needs to be changed to lower.
This issue will be discussed later.
If you have any questions, please correct them!
Kingfish
2005.3.29