// nvml-wrapper@0.8.0/src/device.rs
#[derive(Debug)]
pub struct Device<'nvml> {
device: nvmlDevice_t,
nvml: &'nvml Nvml,
}上の構造体からdeviceを取り出したい
impl FooTrait for Device {
fn bar(&self) {
struct Hack<'a> {
device: nvmlDevice_t,
nvml: &'a ()
}
let d: nvmlDevice_t = unsafe { mem::transmute::<&_, &Hack<'_>>(self).device };
// ...
}
}このコードはやばい:
- 💣 参照を参照に再解釈している1
- 💣 ライフタイム大丈夫?
- 💣 構造体のレイアウトが一致する保証がない
Device#handle() が nvmlDevice_tを返すのですが…
impl FooTrait for Device {
fn bar(&self) {
let d: nvmlDevice_t = unsafe { self.handle() };
// ...
}
}- ✅ ドキュメントはちゃんと読む
Footnotes
-
C++風に言うなら
reinterpret_cast↩