Use printf to customize print objects

2014/08/28 15:12
Reading number 1.2K

TBOX's built-in libc library has its own printf implementation. While supporting all standard formatting parameters, it also has some extensions to support custom formatting parameter printing, such as:

 //Number of output fixed points: 3.14 tb_printf("%{fixed}\n", tb_float_to_fixed(3.14)); //Output ipv4 address: 127.0.0.1 tb_ipv4_t addr; tb_ipv4_set(&addr, "127.0.0.1"); tb_printf("%{ipv4}\n", &addr);

Both of the above are TBOX's built-in object parameter printing. You just need to register the object name and object description function you need to print.

among %{object_name} It refers to the format of customized parameterized object printing. This is an extension of standard formats such as% s and% f, so that you can NSLog(@"%@", object) It is convenient to print the contents of custom objects.

For example, if you want to support custom printing of the following contents:

 typedef struct _rect_t { tb_long_t x; tb_long_t y; tb_size_t w; tb_size_t h; }rect_t; tb_printf("%{rect}\n", &rect);

Then you only need to provide the description function of the corresponding rect object and register it

 //The description function of the rect object, which formats the description content into the cstr and returns the actual string size static tb_long_t tb_printf_rect_func(tb_cpointer_t object,  tb_char_t* cstr, tb_size_t maxn) { // check tb_assert_and_check_return_val(object && cstr && maxn, -1); // the rect rect_t* rect = (rect_t*)object; // format tb_long_t size = tb_snprintf(cstr, maxn - 1, "(x: %ld, y: %ld, w: %lu, h: %lu)",  rect->x, rect->y, rect->w, rect->h); if (size >= 0) cstr[size] = '\0'; // ok? return size; } //Register the printf parameterized printing support of the% {rect} object. Note: It is better to register at the program initialization stage tb_printf_object_register("rect",  tb_printf_rect_func); //Print the rect object information and display: "(x: 10, y: 10, w: 640, h: 480)" rect_t rect = {10, 10, 640, 480}; tb_printf("%{rect}\n", &rect);

Of course, not only printf supports customized parametric object printing, but also printf series supports this feature, such as the following interfaces:

  • tb_printf
  • tb_snprintf
  • tb_vsnprintf
  • tb_wprintf
  • tb_swprintf
  • tb_vswprintf
  • tb_trace_i
  • tb_trace_d
  • tb_trace_e
  • tb_trace_w

Wait, these are user-defined parametric object printing. Each object needs to be registered once.


Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
one Collection
zero fabulous
 Back to top
Top