I am working on a set returning function and have a question about
switching memory contexts. Basically, what I want to know is whether
memory allocated in one context can be referenced when a different
context is current. The docs give examples like:
if (SRF_IS_FIRSTCALL()) { funcctx = SRF_FIRSTCALL_INIT(); oldcontext =
MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate some memory that needs to span calls */ my_ptr = (a_type *) palloc(size);
MemoryContextSwitchTo(oldcontext); }
funcctx = SRF_PERCALL_SETUP();
/* can I now dereference here? Is it necessary to manually switch
to multi_call_memory_ctx? */ some_function(my_ptr[0]); ...
In a related question, do I only need to switch to
multi_call_memory_ctx when allocating memory that needs to be
referenced in subsequent calls? Would the following make sense?
if (SRF_IS_FIRSTCALL()) { funcctx = SRF_FIRSTCALL_INIT();
/* this will be deallocated at the end of the first call, right? */ scratch_ptr = (a_type *)
palloc(size);
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); /* allocate some memory that needs to
spancalls */ my_ptr = (a_type *) palloc(size); MemoryContextSwitchTo(oldcontext);
/* can I dereference my_ptr here? */ func_called_once(scratch_ptr, my_ptr);
...
}
/* per call stuff follows... */
In other words, if I have allocations that only are needed during the
first call, can I allocate them outside of the multi_call_memory_ctx
(so that they do not live past the first call) and only allocate the
memory needed for multiple calls within the multi_call_memory_ctx?
One last question: if I call SPI_finish, on the first call, do I need
to switch contexts in the per-call section? (I saw some example code
that suggested one needs to switch contexts back to
multi_call_memory_ctx after SPI_finish.)
Thanks.
THK
--
Timothy H. Keitt
http://www.keittlab.org/