Is it safe to hold onto string data in C bindings?


#1

The 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)
{
  CAMLparam1(vbar);
  CAMLlocal1(vfoo);
  const char* bar = String_val(vbar);
  vfoo = caml_copy_string("example");
  printf("%s\n", bar); // bad, vbar's data might have moved?
  CAMLreturn(vfoo);
}

(I’m working on a blog post about problems I ran into with C bindings and want to make sure everything is accurate)


#2

Yes, you are correct.


#3

Is he? CAMLparam1(vbar) is supposed to protect the variable vbar until CAMLreturn (or the runtime lock is released).


#4

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.


#5

Yes: as a result it’s still safe to access the string through vbar after the call to caml_copy_string. But bar isn’t protected, so it’s not safe to access the string through bar.


#6

Thanks for the precisions. @BrendanLong In addition to a post, I think clarifications and examples should be added to the manual.


#7

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).