capypad
0 day streak
rust / expert
Snippet

Manual Send/Sync for FFI Wrappers

By default, types containing raw pointers are neither Send nor Sync. To pass them between threads or share references across threads, you must manually implement these marker traits. This requires an 'unsafe' block because the compiler cannot verify that your synchronization logic or pointer management is sound.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct RawBuffer {
ptr: *mut u8,
len: usize,
}
 
// SAFETY: We ensure that access to the buffer is synchronized
// and that the pointer is valid for the duration of its use.
unsafe impl Send for RawBuffer {}
unsafe impl Sync for RawBuffer {}
 
impl RawBuffer {
pub fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
}
Breakdown
1
unsafe impl Send for RawBuffer {}
Asserts that it is safe to transfer ownership of RawBuffer to another thread.
2
unsafe impl Sync for RawBuffer {}
Asserts that it is safe to share references to RawBuffer across multiple threads.