ocaml-ctypes icon indicating copy to clipboard operation
ocaml-ctypes copied to clipboard

Support bindings for custom blocks

Open mwlon opened this issue 2 years ago • 4 comments

As far as I can tell, there is no way in ctypes to return a custom block. I'd imagine this would work something like the following:

binding:

type t = custom_block
let t: t typ = custom_block_t
let foo = foreign "foo" (void @-> returning t)

generated C stub:

value <something>_foo() {
  value x = foo(); // foo is some function calling caml_alloc_custom or caml_alloc_custom_mem
  CAMLreturn(x);
}

Is this already implemented and just something I overlooked? If not, this seems like an important piece of functionality to add.

mwlon avatar Jan 09 '24 19:01 mwlon

This would still require to have foos around which, somehow, return custom_block values, hence, some kind of OCaml-specific C stubs.

What if custom_block_t could (somehow) take the address of a custom_operations as an argument, so any regular C function taking or returning some value (to be extracted from/embedded in a custom_block in the generated stubs) could be used? (Note I didn't give this much thought, it may not be possible at all of course).

NicolasT avatar Mar 16 '24 23:03 NicolasT

@NicolasT I think that approach might not work, since we also need to inform OCaml of size, used, and sometimes max, which might be dynamically determined upon each allocation. Custom blocks are definitely a power-user feature, so it seems reasonable and easier to me if we leave their usage to the user.

mwlon avatar Mar 27 '24 02:03 mwlon

Right. For the use-case I had in mind, the wrapped value is always a pointer itself, so size is a known constant. used and max could be 0 and 1 since I can't know how the actual size of whatever is behind that pointer anyway :)

NicolasT avatar Mar 28 '24 21:03 NicolasT

For that use case, could you just use a ptr void type? I think ctypes handles that out-of-the-box

mwlon avatar Mar 29 '24 02:03 mwlon