[ocaml-ctypes] Passing ocaml strings to C functions
Thomas Braibant
thomas.braibant at gmail.com
Thu May 31 09:41:06 BST 2018
Hi,
I am trying to pass an OCaml string to a C function, in some specific
scenario where I know that the C part will not keep a reference to the
OCaml string after the function returns. Without loss of generality,
the binding would look like
```
module C (F : Cstubs.FOREIGN) = struct
open F
let foo = foreign "fooC" (ptr void @-> size_t @-> returning int);;
end
```
After applying the bindings to the generated stubs, I can write something like
```
module M = C (C_generated)
let foo_wrapped (s : Bigstring.t) =
C.foo
(Ctypes.to_voidp (Ctypes.bigarray_start Array1 s)
(Unsigned.Size_t.of_int (Bigstring.length str))
;;
```
For some reason, I can't seem to find how to apply C.foo to an ocaml string.
```
let foo_wrapped' (s : String.t) =
C.foo
(Ctypes.to_voidp (Ctypes.ocaml_string_start s)
(Unsigned.Size_t.of_int (String.length str))
;;
```
What's more surprising is the error message when trying to coerce the
ptr char and ocaml strings together:
```
Ctypes.(coerce ocaml_string (ptr char) (Ctypes.ocaml_string_start ""))
;;
Exception: Coercion failure: char* is not coercible to char*.
```
What I think is that I could rewrite the binding, to have something like:
```
let foo' = foreign "fooC" (ocaml_string @-> size_t @-> returning int);;
```
but it seems like unnecessary code duplication (and would make my
actual use case harder to write).
Am I missing something here?
Thanks in advance,
Thomas Braibant
More information about the Ctypes
mailing list