Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Parameters of class implementation should be borrowed, not owned #193

Description

@jscissr

Consider the following example:

com::interfaces! {
    #[uuid("12345678-1234-1234-0000-12345678ABCD")]
    pub unsafe interface IEmpty: com::interfaces::iunknown::IUnknown {}

    #[uuid("12345678-1234-1234-0001-12345678ABCD")]
    pub unsafe interface ISomething: com::interfaces::iunknown::IUnknown {
        fn DoSomething(&self, empty: IEmpty);
    }
}

com::class! {
    #[no_class_factory]
    pub class EmptyClass: IEmpty {}
    impl IEmpty for _ {}
}

com::class! {
    #[no_class_factory]
    pub class SomethingClass: ISomething {}
    impl ISomething for _ {
        fn DoSomething(&self, _empty: IEmpty) {} // <---
    }
}

fn main() {
    let empty_instance = EmptyClass::allocate();
    let empty = empty_instance.query_interface::<IEmpty>().unwrap();

    let something_instance = SomethingClass::allocate();
    let something = something_instance.query_interface::<ISomething>().unwrap();

    unsafe { something.DoSomething(&empty); }
}

When you run it, you get thread 'main' panicked at 'Underflow of reference count'.

The problem is that the DoSomething method of SomethingClass takes an owned IEmpty, and thus will implicitly drop it, which decreases the reference count. But this is not what should happen. The callee should not call Release on its parameters; in fact it should call AddRef if it needs to access the interface after the call completes. The caller ensures that the interface is valid during the duration of the call.

To solve this, the marked line should be replaced with the following:

fn DoSomething(&self, _empty: &IEmpty) {}

However this does not compile.

As a temporary workaround, you can call std::mem::forget(_empty) in the class method.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions