Trait objc2::Encode[][src]

pub unsafe trait Encode {
    const ENCODING: Encoding<'static>;
}
Expand description

Types that have an Objective-C type-encoding.

Usually you will want to implement RefEncode as well.

If your type is an opaque type you should not need to implement this; there you will only need RefEncode.

Safety

The type must be FFI-safe, meaning a C-compatible repr (repr(C), repr(u8), repr(transparent) where the inner types are C-compatible, and so on). See the nomicon on other reprs.

Objective-C will make assumptions about the type (like its size and alignment) from its encoding, so the implementer must verify that the encoding is accurate.

Concretely, Self::ENCODING must match the result of running @encode in Objective-C with the type in question.

You should also beware of having Drop types implement this, since when passed to Objective-C via. objc::msg_send! their destructor will not be called!

Examples

Implementing for a struct:

#[repr(C)]
struct MyType {
    a: i32,
    b: bool,
    c: *const c_void,
}

unsafe impl Encode for MyType {
    const ENCODING: Encoding<'static> = Encoding::Struct(
        // The name of the type that Objective-C sees.
        "MyType",
        &[
            // Delegate to field's implementations.
            // The order is the same as in the definition.
            i32::ENCODING,
            bool::ENCODING,
            <*const c_void>::ENCODING,
        ],
    );
}

// Note: You would also implement `RefEncode` for this type.

Associated Constants

The Objective-C type-encoding for this type.

Implementations on Foreign Types

The encoding of isize varies based on the target pointer width.

Encode is implemented manually for *mut c_void, instead of implementing RefEncode, to discourage creating &mut c_void.

Encode is implemented manually for *const c_void, instead of implementing RefEncode, to discourage creating &c_void.

The encoding of usize varies based on the target pointer width.

Implementors