ocaml-ctypes
ocaml-ctypes copied to clipboard
how to call functions taking a variable number of arguments
I have to bind a printf-like function, i.e. a function taking a format string and a list of additional parameters depending on the format string.
Is there a way to do this in ctypes ?
Related to #103.
This is likely to be tricky for reasons that are not really specific to ctypes. What type would you like the function to have on the OCaml side?
The same as the printf functions, using formats :-)
It's possible in theory, at least if the API you're binding exposes something analogous to vprintf. However, it's likely to be quite a bit of work. The implementation of the format type used in OCaml's printf is not entirely trivial:
https://github.com/ocaml/ocaml/blob/trunk/stdlib/camlinternalFormatBasics.ml
Indeed, I thought about doing the same but this would be quite heavy.
I don't know if that may work for your but in tsdl what I did is to use OCaml's pretty printing machinery and simply use the variadic function with a "%s" formatter, see API and implementation.
Nice but in my case, I really need to pass arguments to the openmaple printf functions, because it handles maple objects in formats to turn them into strings :(
Some mechanism for invoking (simple) variadic functions would indeed be great. As per #103, I, too, need to call ioctl(2) and there does not seem to be any way to do it portably from OCaml other than writing my own project-specific C stubs. (Thankfully, since everyone has had to do this for ioctl(2) for decades now, there is at least no shortage of example code out there...)
Hi, @bendiken, I believe that if you only require static arities on the OCaml side, using Ctypes's cstubs support (0.4.0+ iirc) should generate code that works without ABI restriction. If you require the variadicity in OCaml, too, there is a type encoding problem which may need to be resolved.
Out of curiosity, what is the purpose of your ioctl(2) calls? I am interested in libraries for binding systems APIs to OCaml.
@dsheets Thanks—fixed arity (e.g., defining ioctl0, ioctl1, etc, depending on the required number of arguments) would be just fine; I'll have a look at cstubs. ioctl(2) is needed for interfacing to many device drivers; in the immediate matter, V4L2, but generally speaking it's an essential facility for interfacing with hardware (and hypervisors, as it may be).
@dsheets FYI, I decided it would take me longer to figure out Cstubs usage than to just write the pesky stubs, so in this instance I ended up adding basic ioctl(2) support to ExtUnix: https://github.com/ygrek/extunix/pull/11. Will revisit once Cstubs has more documentation.