How to bind to foreign function returning C struct using Ctypes?

I have defined a structure type using Ctypes. When I create a struct on the OCaml side and pass it to C, it works fine. When I try to bind to a function which returns a value of this struct type, I get a segfault error. What is the proper way to bind to a C function returning a struct and access that struct in OCaml? Could you link to or show an example?

1 Like

This is for a returned pointer to a struct, but I have some (last time I used it) working code here in GDAL bindings: https://github.com/hcarty/ocaml-gdal/blob/master/src/warp.ml#L23-L86

That code is using the libffi-based ctypes-foreign bindings rather then stub generation. I’m not sure what practical differences there are between the two binding approaches in this case.

I’d like to reopen this topic because the issue is biting me again. Returning a pointer to a structure is not a problem, because a pointer fits in a CPU register. The ABI is simple. The problem is when the function returns a structure which does not fit in a register. From what I understand, the ABI requires an implicit pointer that becomes the first argument to the function, but I’m not able to create an FFI binding making this pointer explicit. In all cases I get a core dump.

The function I’m trying to write bindings to is objc_msgSend_stret. Any pointers how to implement this binding will be greatly appreciated.

Binding functions that return structs is supported in ctypes, and there are some examples in the test suite.

There’s one restriction that I’m aware of: binding structs with array or union members needs to use stub generation; it’s not supported with the dynamic/foreign interface.

Thank you for replying. I think I figured it out.