From 245e532934fc9a6df18cf246c29c79863d6ce714 Mon Sep 17 00:00:00 2001 From: Nathaniel McCallum Date: Mon, 21 Dec 2015 11:46:32 -0500 Subject: [PATCH] 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. --- doc/apiref.rst | 5 +++++ src/jansson.def | 1 + src/jansson.h | 1 + src/memory.c | 8 ++++++++ test/suites/api/test_memory_funcs.c | 7 ++++++- 5 files changed, 21 insertions(+), 1 deletion(-) diff --git a/doc/apiref.rst b/doc/apiref.rst index a921ef7..0aca86f 100644 --- a/doc/apiref.rst +++ b/doc/apiref.rst @@ -1570,6 +1570,11 @@ behavior is needed. Jansson's API functions to ensure that all memory operations use 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:** Circumvent problems with different CRT heaps on Windows by using diff --git a/src/jansson.def b/src/jansson.def index da4cfd4..c43eb07 100644 --- a/src/jansson.def +++ b/src/jansson.def @@ -66,4 +66,5 @@ EXPORTS json_unpack_ex json_vunpack_ex json_set_alloc_funcs + json_get_alloc_funcs diff --git a/src/jansson.h b/src/jansson.h index 6f7fd07..ee60794 100644 --- a/src/jansson.h +++ b/src/jansson.h @@ -289,6 +289,7 @@ typedef void *(*json_malloc_t)(size_t); typedef void (*json_free_t)(void *); 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 } diff --git a/src/memory.c b/src/memory.c index ca44d6b..e2368cf 100644 --- a/src/memory.c +++ b/src/memory.c @@ -59,3 +59,11 @@ void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn) do_malloc = malloc_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; +} diff --git a/test/suites/api/test_memory_funcs.c b/test/suites/api/test_memory_funcs.c index a760c08..047ca67 100644 --- a/test/suites/api/test_memory_funcs.c +++ b/test/suites/api/test_memory_funcs.c @@ -36,10 +36,15 @@ static void my_free(void *ptr) static void test_simple() { + json_malloc_t mfunc = NULL; + json_free_t ffunc = NULL; + json_set_alloc_funcs(my_malloc, my_free); + json_get_alloc_funcs(&mfunc, &ffunc); 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"); }