Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What's this?
A new module,
Cstubs_structs
, that supports retrieving the layout of structs and unions from C declarations.What problem does it solve?
The current structure description API computes the layout of the structs and unions you describe in your program. This works well in simple cases if you're careful, but there's no check that what you write matches the declared type, and some cases are tricky to handle. For example, there's currently no clear solution for when
How does this change solve the problem?
The new module generates C code that is compiled against the header to retrieve the struct layout information from the C compiler, guaranteeing that the layout of structs used in your OCaml/ctypes program matches the layout in the C library you're binding.
How do I use it?
The interface is very similar to the existing structure description API, and in most cases it should be easy to switch. Let's consider an example. Here's a simple C struct declaration:
You can describe this struct using the existing API as follows:
With the
Cstubs_structs
module in this pull request you put the declaration inside a functor:and then pass the functor to generate a C program:
The C program then an ML module which you can link in to your program:
Isn't the build process rather complex?
Perhaps, but each step has a clear rationale. Generating C is the best way to retrieve information from library headers. Having the C program then generate an ML program makes it possible to inline the retrieved layout information into your program. Using a functor to link the generator and the generated code together makes it possible to give strong guarantees about typing.