Passing structs to C functions
Factor handbook » C library interface » Struct classes

Prev:Creating instances of structs


Structs can be passed and returned by value, or by reference.

If a parameter is declared with a struct type, the parameter is passed by value. To pass a struct by reference, declare a parameter with a pointer to struct type.

C functions returning structs
If a C function is declared as returning a struct type, the struct is returned by value, and wrapped in an instance of the correct struct class automatically. If a C function is declared as returning a pointer to a struct, it will return an alien instance. This is because there is no way to distinguish between a pointer to a single struct and a pointer to an array of zero or more structs. It is up to the caller to wrap it in a struct using memory>struct, or a specialized array of structs using <direct-T-array>, respectively.

An example of a struct declaration:
USING: alien.c-types classes.struct ; STRUCT: Point { x int } { y int } { z int } ;

A C function which returns a struct by value:
USING: alien.syntax ; FUNCTION: Point give_me_a_point ( c-string description )

A C function which takes a struct parameter by reference:
FUNCTION: void print_point ( Point* p )