Skip to content

Commit

Permalink
Keep string alive over C function call (simonjbeaumont#21)
Browse files Browse the repository at this point in the history
* Keep string alive over C function call

To avoid the GC removing a string where C code writes a result, use it
after the call. See also

xapi-project/xen-api@bc053bb

In the commit above, Sys.opaque_identity was used to keep the value
alive. However, it is not available in the OCaml 4.02.3 compiler.

Signed-off-by: Christian Lindig <christian.lindig@citrix.com>

* Use "List.hd [s]" for using s

Signed-off-by: Christian Lindig <christian.lindig@citrix.com>
  • Loading branch information
lindig authored and simonjbeaumont committed Sep 18, 2018
1 parent fae2e60 commit 936cff8
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/pci.ml
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ let with_string ?(size=1024) f =
* to the lifetime of the input parameter, which can be moved
* by the GC and cause problems. *)
let buf = CArray.make char ~initial:'\x00' size in
f (CArray.start buf) size
let s = CArray.start buf in
let r = f s size in
(* Keep `s` alive through the C binding invocation in `f` *)
ignore (List.hd [s] |> Obj.repr |> Obj.tag);
r

let lookup_class_name pci_access class_id =
with_string (fun buf size ->
Expand Down

0 comments on commit 936cff8

Please sign in to comment.