php struct
1.0.0
การใช้งานโครงสร้างใน PHP รองรับการถอดรหัสไฟล์ไบนารี
การสร้างโครงสร้างใหม่
$ myStruct_t = new Struct (
" foo " , uint32_t, //single uint32_t
" baz " , uint8_t, 30 //array of 30 unsigned chars
);คุณสามารถระบุธงสำหรับสมาชิกเช่น:
$ myStruct_t = new Struct (
" beval " , uint32_t, 1 , ENDIAN_BIG , //big endian value
" leval " , uint32_t, 1 , ENDIAN_LITTLE , //little endian value
" myString " , int8_t, 32 , VAR_STRING , //string of 32 characters
" myNumber " , uint32_t, 1 , VAR_NUMERIC , //explicitly uses the PHP's int type
);คุณสามารถใช้ flag_strsz เพื่อระบุว่าสมาชิกนี้จะระบุขนาดของสตริงที่กำลังจะมาถึง
$ string_t = new Struct (
" strSz " , uint32_t, 1 , FLAG_STRSZ , //a string follow, and its length is indicated by this member
" varString " , uint8_t, 0 , //the size will be replaced at runtime due to FLAG_STRSZ
);การใช้ FLAG_STRSZ ทำให้ขนาดโครงสร้างคาดเดาไม่ได้
คุณยังสามารถใช้โครงสร้างที่ซ้อนกันได้:
$ myStruct_t = new Struct (
" foo " , uint32_t, //single uint32_t
" baz " , uint8_t, 30 //array of 30 unsigned chars
);
$ otherStruct_t = new Struct (
" magic " , uint8_t, 4 ,
" elements " , $ myStruct_t , 32 , //creates an array of 32 structures
);โครงสร้างและไฟล์:
// Clone the structure template
$ header = clone ( $ header_t );
// Simple check for proper arguments
if ( $ argc < 2 || ! file_exists ( $ argv [ 1 ])){
fprintf ( STDERR , " File not found! n" );
return 1 ;
}
// Open the specified file in read mode
$ f = fopen ( $ argv [ 1 ], " rb " );
// Get enough data to fill the structure
$ d = fread ( $ f , $ header -> getSize ());
// We don't need the file anymore
fclose ( $ f );
// Put the data we read into the structure
$ header -> apply ( $ d );แยกวิเคราะห์องค์ประกอบ
printf ( " Struct size: %d n" , $ header -> getSize ());
foreach ( $ header -> members as $ name => $ member ){
printf ( " member '%s', value: 0x%x n" , $ name , $ member -> getValue ());
}และสำหรับโครงสร้างซ้อนกัน?
function printStruct ( $ struct ){
foreach ( $ struct -> members as $ name => $ memb ){
$ value = $ memb -> getValue ();
if ( is_array ( $ value )){
if (Struct:: isStructArray ( $ value )){
foreach ( $ value as $ subStruct ){
printStruct ( $ subStruct );
}
} else {
//print array of bytes/elements
printf ( " %s n" , $ name );
var_dump ( $ value );
}
} else {
//print element/value
printf ( " %s => 0x%x n" , $ name , $ value );
}
}
}รับข้อมูลไบนารีของสมาชิก/โครงสร้าง
$ binaryData = $ member -> getData ();การตั้งค่าข้อมูลไบนารีของสมาชิก (ใช้สิ่งนี้เพื่อตั้งค่าสตริง!)
$ member -> setData ( $ binData );รับมูลค่าที่ถอดรหัสของสมาชิก (ตามประเภทของมัน)
$ value = $ member -> getValue ();การตั้งค่าค่าของสมาชิก (จะได้รับการเข้ารหัสตามประเภทของมัน)
หมายเหตุ : สำหรับสตริงใช้ setData หรือคุณจะต้องผ่านอาร์เรย์ถ่านไปยังฟังก์ชันนี้
$ member -> setValue ( $ value );