OCaml C binding documentation says that you need to copy any string parameters before releasing the runtime lock.
Am I correct in assuming that this is a generalization of a rule that you shouldn’t hold onto the result of String_val after any function that could allocate? i.e. this is also bad:
value example(value vbar)
const char* bar = String_val(vbar);
vfoo = caml_copy_string("example");
printf("%s\n", bar); // bad, vbar's data might have moved?
(I’m working on a blog post about problems I ran into with C bindings and want to make sure everything is accurate)
Yes, you are correct.
CAMLparam1(vbar) is supposed to protect the variable
CAMLreturn (or the runtime lock is released).
My understanding is that these macros are used to register the local roots with the GC so they can be found and updated when the GC moves the value they point to, but by themselves they don’t keep their values from being moved.
Yes: as a result it’s still safe to access the string through
vbar after the call to
bar isn’t protected, so it’s not safe to access the string through
Thanks for the precisions.
@BrendanLong In addition to a post, I think clarifications and examples should be added to the manual.
Great, thanks for the information everyone!
Yeah, that makes sense. I think I’ll see if I can clarify the manual at all, and also make a blog post (it can’t hurt to have more info available when people search for their error messages).
I’ve been super busy for a while, but here’s the blog post:
I recently spent several days at work improving the OCaml FreeTDS C bindings for work, and I thought it might be useful to share the problems I ran into and how to solve them. I tried to order things so the most likely issues are listed first, but if...
(And the code I was working on when I wrote this will show up in our Mssql library as soon as I have time)