How do I initialize a CompositionTarget to null using the Rust Crate for Windows?

Viewed 69

Specifically, what is the correct way to initialize the CompositionTarget member in the following Rust Crate for Windows CoreApp code excerpt?

#[implement(Windows::ApplicationModel::Core::IFrameworkView)]
struct AppView {
    target: CompositionTarget,
}
        
#[allow(non_snake_case)]
impl AppView {
    fn new() -> Self { //
        Self {
            //target: std::ptr::null_mut(),
            //target: CompositionTarget(0),
        }
    }
      
    fn Initialize(&self, _: &Option<CoreApplicationView>) -> Result<()> {
        Ok(())
    }
        
    fn Load(&self, _: &HSTRING) -> Result<()> {
        Ok(())
    }
        
    fn Uninitialize(&self) -> Result<()> {
        Ok(())
    }
      
    fn Run(&self) -> Result<()> {
        let window = CoreWindow::GetForCurrentThread()?;
        window.Activate()?;
      
        let dispatcher = window.Dispatcher()?;
        dispatcher.ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit)?;

        Ok(())
    }
        
    fn SetWindow(&self, _: &Option<CoreWindow>) -> Result<()> {
        let compositor = Compositor::new()?;
        let root = compositor.CreateContainerVisual()?;
        //...
        Ok(())
    }
}
        
fn main() -> Result<()> {
    unsafe {
        CoInitializeEx(std::ptr::null_mut(), COINIT_MULTITHREADED)?;
    }
       
    let app: IFrameworkViewSource = App().into();
    CoreApplication::Run(app)?;
    Ok(())
}
1 Answers

Rust does not have null. Instead, you should use Option:

struct AppView {
    target: Option<CompositionTarget>,
}

impl AppView {
    fn new() -> Self {
        Self {
            target: None,
        }
    }
    ...

This works well since in the windows crate a CompositionTarget cannot be null, any function that would return a null value will return an Option::None or Err(Error::Ok) instead. See this issue.

Related