Gabriel Southern
Gabriel Southern

Reputation: 10073

Understanding "warning: use of `#[derive]` with a raw pointer" warning

Summary

I'm trying to understand what the following warning means and what the best way to silence it is if there's not an actual problem with my code.

warning: use of `#[derive]` with a raw pointer, #[warn(raw_pointer_derive)] on by default

Details

I am mostly interested in understanding what this warning means, but the details of why I am seeing it are that I have some library code written in Go and I have exported that code and want to call it from Rust. As of version 1.5, Go has an option to generate a C interface. This includes a generated header file that contains the declaration:

typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;

I also have an exported function in the generated C file that uses this struct:

extern GoUint64 Foo(GoSlice p0);

To call this function from Rust I create a struct as follows:

#[repr(C)]
#[derive(Copy, Clone)]
pub struct GoSlice {
    pub data: *const u64,
    pub len:  c_long,
    pub cap:  c_long,
}

I also import the function as:

extern fn Foo(data: GoSlice) -> c_ulong;

Then when I use the function I do something like:

fn call_foo(arr: &[u64]) -> u64 {
    let res: u64;
    let go_slice = GoSlice {
        data: arr.as_ptr(),
        len: arr.len() as i64,
        cap: arr.len() as i64
    };
    unsafe {
        res = Foo(go_slice);
    }
    return res;
}

So I think that I need the go_slice object to be copied, which is why I added the #[derive(Copy, Clone)], but I'm not certain whether the warning means there is a real problem or not. If not, I'd like to silence it if possible, and if there's an actual problem then I want to fix my code.

I'm using rust nightly and this warning happens with rustc 1.4.0-nightly (20a8412e0 2015-08-28)

Upvotes: 2

Views: 168

Answers (1)

Eli Friedman
Eli Friedman

Reputation: 2393

Basically, the warning is just "this looks suspicious: can you really clone this struct by just copying the raw pointer?". If you're sure what you're doing is actually right, you can just implement Copy and Clone by hand.

In this particular case... you probably shouldn't be trying to manipulate a Go slice from Rust code in the first place. You probably want to pass in a raw pointer from the Rust side, and convert it to a slice in Go code. Otherwise, the next person who comes along to modify the Go code is going to assume that the lifetime of the slice is managed by the Go garbage collector.

Upvotes: 3

Related Questions