Skip to content

Call a C++ method which is only safe Rust for some pointer types #32

@teor2345

Description

@teor2345

An interop API has the following properties:

  • a C++ method is safe to call in Rust on some pointer/reference types, but unsafe on others
  • the Rust methods should have the same name, because the underlying C++ method is the same
  • in Rust, the unsafe method will be called in an unsafe block, so using a suffixed name is redundant:
unsafe { MyCppType::do_the_thing_unsafe() }
Example Code

This can be supported using inherent trait impls and trait-based Rust method name overloading. This allows writing the same method name with two different receiver types, one safe and one unsafe:

pub struct MyCppType;

impl MyCppType {
    fn do_the_thing(&mut self) { ... }
}

trait MyCppTypeUnsafe {
    unsafe fn do_the_thing(self: CMut<'_, Self>);
}

#[inherent]
impl MyCppTypeUnsafe for MyCppType { ... }

Calls look like:

unsafe { MyCppTypeUnsafe::do_the_thing(...) }
MyCppType::do_the_thing(...)
<MyCppType as Self>::do_the_thing(...)
Rust Compiler Features
Sources

Metadata

Metadata

Assignees

No one assigned

    Labels

    use caseA Rust/C++ interop usage example

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions