Chinaunix首页 | 论坛 | 博客
  • 博客访问: 14021
  • 博文数量: 18
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 190
  • 用 户 组: 普通用户
  • 注册时间: 2021-06-07 17:12
个人简介

对嵌入式、QT、桌面开发感兴趣

文章分类
文章存档

2023年(2)

2022年(16)

我的朋友

分类: C/C++

2022-09-09 09:50:08

要确定 cjson 对象保存的是指针还是字符串内容,写了如下测试代码

  1. /*
  2.  * 测试 cJSON_AddStringToObject 保存的是指针还是内容
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include "cJSON.h"

  7. int main() {
  8.     cJSON *json = cJSON_CreateObject();
  9.     cJSON * string = NULL;
  10.     char str[128] = {0};

  11.     strcpy(str, "Hello World");
  12.     cJSON_AddStringToObject(json, "string", str);
  13.     memset(str, 0x00, sizeof(str));
  14.     string = cJSON_GetObjectItem(json, "string");

  15.     printf("str is [%s], string is [%s]\n", str, cJSON_GetStringValue(string));
  16.     cJSON_Delete(json);
  17.     return 0;
  18. }
输出内容为

  1. str is [], string is [Hello World]

可见 cjson 对象保存的是字符串内容

其实只需要看 cJSON 源代码就可以了

  1. CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
  2. {
  3.     cJSON *string_item = cJSON_CreateString(string);
  4.     if (add_item_to_object(object, name, string_item, &global_hooks, false))
  5.     {
  6.         return string_item;
  7.     }

  8.     cJSON_Delete(string_item);
  9.     return NULL;
  10. }

  11. CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
  12. {
  13.     cJSON *item = cJSON_New_Item(&global_hooks);
  14.     if(item)
  15.     {
  16.         item->type = cJSON_String;
  17.         item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
  18.         if(!item->valuestring)
  19.         {
  20.             cJSON_Delete(item);
  21.             return NULL;
  22.         }
  23.     }

  24.     return item;
  25. }

  26. static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
  27. {
  28.     size_t length = 0;
  29.     unsigned char *copy = NULL;

  30.     if (string == NULL)
  31.     {
  32.         return NULL;
  33.     }

  34.     length = strlen((const char*)string) + sizeof("");
  35.     copy = (unsigned char*)hooks->allocate(length);
  36.     if (copy == NULL)
  37.     {
  38.         return NULL;
  39.     }
  40.     memcpy(copy, string, length);

  41.     return copy;
  42. }



阅读(1450) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~