Skip to content

Instantly share code, notes, and snippets.

@KisaragiEffective
Last active August 15, 2022 17:01
Show Gist options
  • Select an option

  • Save KisaragiEffective/58d5fb5d839015f74d5941c1f6a84698 to your computer and use it in GitHub Desktop.

Select an option

Save KisaragiEffective/58d5fb5d839015f74d5941c1f6a84698 to your computer and use it in GitHub Desktop.

ドキュメントはちゃんと読め (n)

前提

// 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

  1. C++風に言うならreinterpret_cast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment