The most powerful feature of the Types plugin is the ability to map C structs to JSON strings for storage. This is achieved via two callback-based functions:
ef_set_struct: Converts a C structure into a JSON string using a provided ef_types_set_cb callback, then stores it.ef_get_struct: Retrieves the JSON string for a key and uses an ef_types_get_cb callback to reconstruct the C structure.
Note: The memory allocated for the structure returned by ef_get_struct must be manually freed using the free_fn provided in your S2jHook during initialization.
/* Example: Storing and retrieving a Student struct */
// 1. Define your structures
typedef struct {
char name[16];
} Hometown;
typedef struct {
uint8_t id;
double weight;
uint8_t score[8];
char name[16];
Hometown hometown;
} Student;
// 2. Define the callback to convert Struct -> JSON
static cJSON *stu_set_cb(void* struct_obj) {
Student *struct_student = (Student *)struct_obj;
s2j_create_json_obj(json_student);
s2j_json_set_basic_element(json_student, struct_student, int, id);
s2j_json_set_basic_element(json_student, struct_student, double, weight);
s2j_json_set_array_element(json_student, struct_student, int, score, 8);
s2j_json_set_basic_element(json_student, struct_student, string, name);
s2j_json_set_struct_element(json_hometown, json_student, struct_hometown, struct_student, Hometown, hometown);
s2j_json_set_basic_element(json_hometown, struct_hometown, string, name);
return json_student;
}
// 3. Define the callback to convert JSON -> Struct
static void *stu_get_cb(cJSON* json_obj) {
s2j_create_struct_obj(struct_student, Student);
s2j_struct_get_basic_element(struct_student, json_obj, int, id);
s2j_struct_get_array_element(struct_student, json_obj, int, score);
s2j_struct_get_basic_element(struct_student, json_obj, string, name);
s2j_struct_get_basic_element(struct_student, json_obj, double, weight);
s2j_struct_get_struct_element(struct_hometown, struct_student, json_hometown, json_obj, Hometown, hometown);
s2j_struct_get_basic_element(struct_hometown, struct_student, string, name);
return struct_student;
}
// 4. Usage
Student orignal_student = {
.id = 24,
.weight = 71.2,
.score = {1, 2, 3, 4, 5, 6, 7, 8},
.name = "StudentName",
.hometown.name = "HometownName",
};
// Store
ef_set_struct("student_key", &orignal_student, stu_set_cb);
// Retrieve
Student *student = ef_get_struct("student_key", stu_get_cb);
// Cleanup
s2jHook.free_fn(student);