pub unsafe trait Encode {
const ENCODING: Encoding;
}
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 = 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§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Source§impl Encode for AtomicIsize
Available on target_has_atomic=ptr
only.
impl Encode for AtomicIsize
target_has_atomic=ptr
only.Source§impl Encode for AtomicUsize
Available on target_has_atomic=ptr
only.
impl Encode for AtomicUsize
target_has_atomic=ptr
only.