Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Ocaml bindings stubs from C header file

Tags:

ocaml

idl

I have a header file which declares a C API for some library and I would like to create an OCaml bindings for this lib. I found that camlidl can create stubs from an IDL file but as I understand there is no automatic conversion from a *.h file to IDL, so now I wonder if there is any other way to generate stubs for OCaml bindings from a C header file?

like image 503
Nutel Avatar asked Oct 29 '11 22:10

Nutel


1 Answers

There is not enough information in a C header file to write bindings for another language. In very simple cases (for example, all functions take only integer or floating-point arguments), it's possible, but as soon as pointers get involved, you need to provide more information: will the function read from the pointed-to value, write to it, or both? Must the interface allow a null pointer? Is this in fact a pointer to an array, and where's the size? Is this char* a pointer to a zero-terminated string?

IDL expands C function declarations with extra annotations to cover all these points. That's why camlidl works on IDL and not directly on C headers. You won't find anything significantly less painful.

There's another approach, which is to liberally annotate your C headers with macros that have an empty expansion but provide extra type information, e.g.

int memmove(void ANN_OUT ANN_SIZE(n) ANN_NOT_NULL *dest,
            const void ANN_IN ANN_SIZE(n) ANN_NOT_NULL *src,
            size_t n);

Such annotations are not standardized, so if you go this route you'll have to write your own tools. (Look up Cil if you want to parse C.) I recommend that instead you treat the IDL declarations as primary, and generate the C header files from them.

like image 116
Gilles 'SO- stop being evil' Avatar answered Oct 19 '22 19:10

Gilles 'SO- stop being evil'