-->

How one deals with typedefs in Squeak FFI

2019-07-23 07:02发布

问题:

I want to interface with a library (HDF5) which uses exclusively its own typedefs in both function prototypes and structure definitions.

typedef struct {
    H5L_type_t          type;           /* Type of link                   */
    hbool_t             corder_valid;   /* Indicate if creation order is valid */
    int64_t             corder;         /* Creation order                 */
    H5T_cset_t          cset;           /* Character set of link name     */
    union {
        haddr_t         address;        /* Address hard link points to    */
        size_t          val_size;       /* Size of a soft link or UD link value */
    } u;
} H5L_info_t;

In Visualworks with DLLCC I can deal with such typedefs like this:

H5Interface>>hbool_t
    <C: typedef unsigned int hbool_t>

And I can then use hbool_t in both prototypes and structure, same for enum.

But Squeak FFI seems to understand only a few atomic types and interpret anything else as a structure. Obviously, someone has to do the translation, and if it is not automated, then it's both errorprone and not robust to future evolutions of external library.

So what is the recommended way for avoiding such fragility?

回答1:

It seems that there is an obscure feature for handling aliases (typedef)

Create a new ExternalStructure class

ExternalStructure subclass: #'Hbool_t'
    instanceVariableNames: ''
    classVariableNames: ''
    poolDictionaries: ''
    category: 'FFI-Tests'

Then create fields method with nil and aliased type

Hbool_t class>>fields
    ^#( nil 'ulong' )

Do Hbool_t defineFields and now 'Hbool_t' is a registered type, and can be used in other structure definition and in function prototypes.

It's not exactly 'hbool_t', but it is better than direct replacement by ulong.