Ed McCardell
Ed McCardell

Reputation: 23

Rust FFI Signature conversion for const pointers

I have a C library with functions, operating on an opaque struct, defined like this:

Foo* makeFoo(); // create a new Foo
Foo* dupFoo(const Foo* orig); // make a duplicate Foo

rust-bindgen creates these extern definitions:

pub fn makeFoo() -> *mut Foo;
pub fn dupFoo(orig: *Foo) -> *mut Foo;

Now, I don't expect the following to work:

unsafe {
    let x = makeFoo();
    // Do some stuff with x
    let y = dupFoo(x);
}

and indeed there is an error mismatched types: expected '*Foo' but found '*mut Foo' (values differ in mutability)

What is the recommended way to handle translating these types of C function signatures?

What does seem to work is either changing the parameter types -- even when the C function uses const -- to *mut Foo, or using transmute:

unsafe {
    let x = makeFoo();
    // Do some stuff with x
    let cx: *Foo = mem::transmute(x);
    let y = dupFoo(cx);
}

but I don't know which is better.

Upvotes: 2

Views: 811

Answers (1)

Chris Morgan
Chris Morgan

Reputation: 90752

*T and *mut T are no different from one another; they are merely there as indicators of intent. You can freely cast between them: x as *Foo.

Upvotes: 1

Related Questions