Android native C++快速打印复杂结构体内容

文章介绍了如何使用CLang的__builtin_dump_struct编译器内置函数来快速打印结构体内容,以及在AndroidnativeC++环境中,当printf无法正常工作时,如何自定义myPrint函数进行日志输出。同时,文章提到了list_for_each_entry宏在遍历链表并访问结构体成员中的应用。
摘要由CSDN通过智能技术生成
#ifndef __has_builtin       // Optional of course.
#define __has_builtin(x) 0  // Compatibility with non-clang compilers.
#endif
#if __has_builtin(__builtin_dump_struct))
        __builtin_dump_struct(your_struct_point, &printf);
#endif

!!!不用再挨个变量加print了!!!

使用如上代码就可以利用编译器函数来实现快速打印结构体内容。

学习CLang编译器内置函数: ​https://clang.llvm.org/docs/LanguageExtensions.html

如果在安卓native c++,printf打印不出东西,那么就要自己定义printf。

int myPrint(const char *pFormat, ...)
{
    char logText[MAXLOGLEN];
    va_list args;
    va_start(args, pFormat);
    vsnprintf(logText, MAXLOGLEN, pFormat, args);
    va_end(args);
    __android_log_write(ANDROID_LOG_ERROR, "chwit", logText);
    return 0;
}
或者用一个string去保存打印的字符串,最后再统一输出:
string chwit_str;
int myPrint(const char *pFormat, ...)
{
    char logText[MAXLOGLEN];
    va_list args;
    va_start(args, pFormat);
    vsnprintf(logText, MAXLOGLEN, pFormat, args);
    va_end(args);
    // __android_log_write(ANDROID_LOG_ERROR, "chwit", logText);
    chwit_str += logText;
    return 0;
}

本质:A.获取链表头,B.判断链表项是不是链表头,C.指向链表的下一项。

 * list_for_each_entry - iterate over list of given type
 * @pos: the type * to use as a loop cursor.
 * @head: the head for your list.
 * @member: the name of the list_struct within the struct.
 */

#define list_for_each_entry(pos, head, member) \A.获取链表头,B.判断链表项是不是链表头,C.指向链表的下一项。
for (pos = list_first_entry(head, typeof(*pos), member); \
&pos->member != (head); \
pos = list_next_entry(pos, member))

作用: 循环遍历每个pos实例中的member成员,在大多数情况下member成员是一个链表节点(list_head node)

其实list_for_each_entry就是遍历链表(list_head)的每个节点,返回每个节点所在的数据结构实例,另外还有一个宏

list_for_each_entry遍历的链表,其每一项都是某个结构体中的成员,单纯遍历链表还不行,还要找到包含这个
链表项的结构体的地址,从而为下一步应用该结构体做好准备。

将for循环分解为以下三点:

1. for循环初始化     pos = list_first_entry(head, typeof(*pos), member);

2. for循环执行条件  &pos->member != (head);

3. 每循环一次执行   list_next_entry(pos, member))

解析:

pos = list_first_entry(head, typeof(*pos), member); ,因为list_first_entry第二个参数是typeof(* pos)。

     typeof()是取变量的类型,这里是取指针pos所指向数据的类型

结构体pos中包含链表member,遍历pos中的member成员。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值