Attribute Macro interoptopus_proc::ffi_type[][src]

#[ffi_type]
Expand description

Enable a struct or enum to appear in generated bindings.

This will derive CTypeInfo based on the visible information in the type definition. This is the preferred way of enabling FFI types; although in some cases (e.g., when dealing with types outside of your control) you will have to implement a surrogate manually, see below.

A number of attributes are available:

AttributeOnExplanation
name="X"struct,enumUses name as the base interop name instead of the item’s Rust name.1
namespace="X"struct,enumDetermine which namespace or file item should go. 2
skip(x)struct,enumSkip field or variant x in the definition, e.g., some x of PhantomData. ⚠️
patterns(p)struct,enumMark this type as part of a pattern, see below. 2
opaquestructCreates an opaque type without fields. Can only be used behind a pointer.
surrogates(x="f")structInvoke function f to provide a CTypeInfo for field x, see below. ⚠️
visibility(x="v")structOverride visibility for field x as public or private; _ means all fields. 2
debug*Print generated helper code in console.
unsafe*Unlocks unsafe options marked: ⚠️

1 While a type’s name must be unique (even across modules) backends are free to further transform this name, e.g., by converting MyVec to LibraryMyVec. In other words, using name will change a type’s name, but not using name is no guarantee the final name will not be modified.

2 Will not be reflected in C backend, but available to languages supporting them, e.g., C# will emit field visibility and generate classes from service patterns.

⚠️ This attribute can lead to undefined behavior when misapplied. You should only suppress fields that have no impact on the type layout (e.g., zero-sized Phantom data). When using surrogates you must ensure the surrogate matches.

Including Types

In contrast to functions and constants types annotated with #[ffi_type] will be detected automatically and do not have to be explicitly mentioned for the definition of the inventory!().

Surrogates

When dealing with types outside of your control you will not be able to implement CTypeInfo for them. Instead you need a surrogate, a helper function which returns that info for the type.

The surrogate’s signature is:

fn some_foreign_type() -> CType {
    // Return an appropriate CType
}

Patterns

Patterns allow you to write, and backends to generate more idiomatic code. The following patterns are currently supported by this annotation:

PatternOnExplanation
success_enumenumDenotes this as a SuccessEnum.

Examples

use interoptopus::ffi_type;

#[ffi_type(opaque, name = "MyVec")]
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct Vec2f32 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}