Trait objc2_encode::Encode
source · [−]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 repr
s.
Objective-C will make assumptions about the type (like its size, alignment and ABI) 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. objc2::msg_send!
their destructor will not be
called!
Examples
Implementing for a struct:
#[repr(C)]
struct MyType {
a: i32,
b: f64,
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,
f64::ENCODING,
<*const c_void>::ENCODING,
],
);
}
// Note: You would also implement `RefEncode` for this type.
Required Associated Constants
Implementations on Foreign Types
sourceimpl Encode for ()
impl Encode for ()
To allow usage as the return type of generic functions.
You should not rely on this encoding to exist for any other purpose (since
()
is not FFI-safe)!
sourceimpl Encode for bool
impl Encode for bool
Using this directly is heavily discouraged, since the type of BOOL differs across platforms.
Use objc2::runtime::Bool::ENCODING
instead.