cJSON学习笔记


cJSON学习笔记

cJSON 总共有以下 8 种数据类型:

/* cJSON Types: */
/*
* 用 8-bit 表示 8 种数据类型
*/
#define cJSON_Invalid (0)
#define cJSON_False  (1 << 0)
#define cJSON_True   (1 << 1)
#define cJSON_NULL   (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array  (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw    (1 << 7) /* raw json */

Hooks

该项目在调用内存分配、清理函数时用到了Hook技术。

  1. 先定义 internal_hooks 数据结构,在结构体内声明 allocate,deallocate,reallocate这3个函数。

    typedef struct internal_hooks
    {
        /* 分配 */
        void *(CJSON_CDECL *allocate)(size_t size);
        /* 解除 */
        void (CJSON_CDECL *deallocate)(void *pointer);
        /* 重分配 */
        void *(CJSON_CDECL *reallocate)(void *pointer, size_t size);
    } internal_hooks;
  2. 特殊处理 MSVC error C2322

    #if defined(_MSC_VER)
    /* work around MSVC error C2322: '...' address of dllimport '...' is not static */
    static void * CJSON_CDECL internal_malloc(size_t size)
    {
        return malloc(size);
    }
    static void CJSON_CDECL internal_free(void *pointer)
    {
        free(pointer);
    }
    static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
    {
        return realloc(pointer, size);
    }
    #else
    #define internal_malloc malloc
    #define internal_free free
    #define internal_realloc realloc
    #endif
  3. 定义global_hooks

    static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
  4. 初始化global_hooks

    CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
    {
        if (hooks == NULL)
        {
            /* 分配默认使用 malloc, free, realloc */
            /* Reset hooks */
            global_hooks.allocate = malloc;
            global_hooks.deallocate = free;
            global_hooks.reallocate = realloc;
            return;
        }
    
        /* 可自定义 hooks */
        global_hooks.allocate = malloc;
        if (hooks->malloc_fn != NULL)
        {
            global_hooks.allocate = hooks->malloc_fn;
        }
    
        global_hooks.deallocate = free;
        if (hooks->free_fn != NULL)
        {
            global_hooks.deallocate = hooks->free_fn;
        }
    
        /* use realloc only if both free and malloc are used */
        global_hooks.reallocate = NULL;
        if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
        {
            global_hooks.reallocate = realloc;
        }
    }

文章作者: 李立基
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 李立基 !
  目录