Skip to content

Struct by value support for FFI #3835

Open
@ankane

Description

@ankane

Hi, while it isn't super common, it'd be nice to support passing and retrieving structs by value with FFI.

require "ffi"

module Hello
  extend FFI::Library
  ffi_lib "./libhello.dylib"

  class World < ::FFI::Struct
    layout :a, :int, :b, :int
  end

  attach_function :get_struct, [], World.by_value
  attach_function :print_struct, [World.by_value], :void
end

Hello.print_struct(Hello.get_struct)

Code for shared library

// gcc -shared -o libhello.dylib hello.c

#include <stdio.h>

struct World {
    int a;
    int b;
};

struct World get_struct(void) {
    struct World w = { .a = 1, .b = 2 };
    return w;
}

void print_struct(struct World w) {
    printf("a = %d, b = %d\n", w.a, w.b);
}

CRuby outputs:

a = 1, b = 2

TruffleRuby 24.2.0 currently errors with:

unknown simple type 'STRUCT_BY_VALUE' (Polyglot::ForeignException)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions