[ffi] Support passing and returning composites (structs) by value.

I wanted to writing bindings for libclang (so that I can generate bindings from C/C++ header files automatically), but I discovered that libclang API uses structs passed and returned by value.

typedef struct {
  unsigned int_data[4];
  void *ptr_data;
} CXToken;

typedef struct {
  const void *data;
  unsigned private_flags;
} CXString;

CINDEX_LINKAGE CXString clang_getTokenSpelling(CXTranslationUnit, CXToken);

So I can’t really bind to this API. There are some interesting design problems to resolve: e.g. when a structure is returned by value who manages the memory of that struct and how do we prevent people from making a mistake of passing address of that struct to some other method.

Author: Fantashit

1 thought on “[ffi] Support passing and returning composites (structs) by value.

  1. The Data struct with a single int field is treated as a single int field in the Linux ABI.

    You’re storing the value of the int field as the address of the Pointer, most likely ptr.address will give you the value of the int field.

    This will not work for structs that are larger than the architecture size (larger than 8 bytes on 64 bit architectures), and this will not work for structs containing floats.

Comments are closed.