Add json_get_alloc_funcs() to allow alloc function fetching

This is particularly useful in modular situations where the allocation
functions are either unknown or private. For instance, in such cases,
the caller of json_dumps() has no way to free the returned buffer.
This commit is contained in:
Nathaniel McCallum 2015-12-21 11:46:32 -05:00
parent e44b2231b5
commit 245e532934
5 changed files with 21 additions and 1 deletions

View File

@ -1570,6 +1570,11 @@ behavior is needed.
Jansson's API functions to ensure that all memory operations use Jansson's API functions to ensure that all memory operations use
the same functions. the same functions.
.. function:: void json_get_alloc_funcs(json_malloc_t *malloc_fn, json_free_t *free_fn)
Fetch the current malloc_fn and free_fn used. Either parameter
may be NULL.
**Examples:** **Examples:**
Circumvent problems with different CRT heaps on Windows by using Circumvent problems with different CRT heaps on Windows by using

View File

@ -66,4 +66,5 @@ EXPORTS
json_unpack_ex json_unpack_ex
json_vunpack_ex json_vunpack_ex
json_set_alloc_funcs json_set_alloc_funcs
json_get_alloc_funcs

View File

@ -289,6 +289,7 @@ typedef void *(*json_malloc_t)(size_t);
typedef void (*json_free_t)(void *); typedef void (*json_free_t)(void *);
void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn); void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn);
void json_get_alloc_funcs(json_malloc_t *malloc_fn, json_free_t *free_fn);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -59,3 +59,11 @@ void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn)
do_malloc = malloc_fn; do_malloc = malloc_fn;
do_free = free_fn; do_free = free_fn;
} }
void json_get_alloc_funcs(json_malloc_t *malloc_fn, json_free_t *free_fn)
{
if (malloc_fn)
*malloc_fn = do_malloc;
if (free_fn)
*free_fn = do_free;
}

View File

@ -36,10 +36,15 @@ static void my_free(void *ptr)
static void test_simple() static void test_simple()
{ {
json_malloc_t mfunc = NULL;
json_free_t ffunc = NULL;
json_set_alloc_funcs(my_malloc, my_free); json_set_alloc_funcs(my_malloc, my_free);
json_get_alloc_funcs(&mfunc, &ffunc);
create_and_free_complex_object(); create_and_free_complex_object();
if(malloc_called != 1 || free_called != 1) if (malloc_called != 1 || free_called != 1
|| mfunc != my_malloc || ffunc != my_free)
fail("Custom allocation failed"); fail("Custom allocation failed");
} }