How to pass a Reference / Pointer to a Rust Struct to a C ffi interface? - pointers

What I am trying to do
I have built a Rust interface, with which I want to interact via C (or C# but it does not really matter for the sake of the question). Because it does not seem to be possible to make a Rust Struct accessible to C I am trying to build some wrapper functions that I can call and that will create the Struct in Rust, call functions of the struct and eventually free the Struct from memory manually.
In order to do this I thought I would pass the pointer to the Struct instance that I create in the init function back to C (or C# and temporary store it as an IntPtr). Then when I call the other functions I would pass the pointer to Rust again, dereference it and call the appropriate functions on the dereferenced Struct, mutating it in the process.
I know that I will have to use unsafe code to do this and I am fine with that. I should probably also point out, that I don't know a lot about life-time management in Rust and it might very well be, that what I am trying to is impossible, because it is quite easy to produce a loose pointer somewhere. In that case, I would wonder how I would need to adjust my approach, because I think I am not the first person who is trying to mutate some sort of state from C inside Rust.
What I tried first
So first of all I made sure to output the correct library and add my native functions to it. In the Cargo.toml I set the lib type to:
[lib]
crate-type = ["cdylib"]
Then I created some functions to interact with the struct and exposed them like this:
#[no_mangle]
pub extern fn init() -> *mut MyStruct {
let mut struct_instance = MyStruct::default();
struct_instance.init();
let raw_pointer_mut = &mut struct_instance as *mut MyStruct;
return raw_pointer_mut;
}
#[no_mangle]
pub extern fn add_item(struct_instance_ref: *mut MyStruct) {
unsafe {
let struct_instance = &mut *struct_instance_ref;
struct_instance.add_item();
}
}
As you can see in the init function I am creating the struct and then I return the (mutable) pointer.
I then take the pointer in the add_item function and use it.
Now I tried to test this implementation, because I had some doubts about the pointer still beeing valid. In another Rust module I loaded the .dll and .lib files (I am on Windows, but that should not matter for the question) and then called the functions accordingly like so:
fn main() {
unsafe {
let struct_pointer = init();
add_item(struct_pointer);
println!("The pointer adress: {:?}", struct_pointer);
}
}
#[link(name = "my_library.dll")]
extern {
fn init() -> *mut u32;
fn add_item(struct_ref: *mut u32);
}
What happened: I did get some memory adress output and (because I am actually creating a file in the real implementation) I could also see that the functions were executed as planned. However the Struct's fields seem to be not mutated. They were basically all empty, what they should not have been after I called the add_item function (and also not after I called the init function).
What I tried after that
I read a bit on life-time management in Rust and therefore tried to allocate the Struct on the heap by using a Box like so:
#[no_mangle]
pub extern fn init() -> *mut Box<MyStruct> {
let mut struct_instance = MyStruct::default();
struct_instance.init();
let raw_pointer_mut = &mut Box::new(struct_instance) as *mut Box<MyStruct>;
return raw_pointer_mut;
}
#[no_mangle]
pub extern fn add_box(struct_instance_ref: *mut Box<MyStruct>) {
unsafe {
let struct_instance = &mut *struct_instance_ref;
struct_instance.add_box();
}
}
unfortunately the result was the same as above.
Additional Information
I figured it might be good to also include how the Struct is made up in principle:
#[derive(Default)]
#[repr(C)]
pub struct MyStruct{
// Some fields...
}
impl MyStruct{
/// Initializes a new struct.
pub fn init(&mut self) {
self.some_field = whatever;
}
/// Adds an item to the struct.
pub fn add_item(
&mut self,
maybe_more_data: of_type // Obviously the call in the external function would need to be adjusted to accomodate for that...
){
some_other_function(self); // Calls another function in Rust, that will take the struct instance as an argument and mutate it.
}
}

Rust has a strong notion of ownership. Ask yourself: who owns the MyStruct instance? It's the struct_instance variable, whose lifetime is the scope of the init() function. So after init() returns, the instance is dropped and an invalid pointer is returned.
Allocating the MyStruct on the heap would be the solution, but not in the way you tried: the instance is moved to the heap, but then the Box wrapper tied to the same problematic lifetime, so it destroys the heap-allocated object.
A solution is to use Box::into_raw to take the heap-allocated value back out of the box before the box is dropped:
#[no_mangle]
pub extern fn init() -> *mut MyStruct {
let mut struct_instance = MyStruct::default();
struct_instance.init();
let box = Box::new(struct_instance);
Box::into_raw(box)
}
To destroy the value later, use Box::from_raw to create a new Box that owns it, then let that box deallocate its contained value when it goes out of scope:
#[no_mangle]
pub extern fn destroy(struct_instance: *mut MyStruct) {
unsafe { Box::from_raw(struct_instance); }
}
This seems like a common problem, so there might be a more idiomatic solution. Hopefully someone more experienced will chime in.

I'm adding a simple answer for anyone who comes across this question but doesn't need to box - &mut struct_instance as *mut _ is the correct syntax to get a mutable pointer to a struct on the stack. This syntax is a bit tricky to find documented anywhere, it's easy to miss the initial mut.
Notably, this does not solve the original poster's issue, as returning a pointer to a local is undefined behavior. However, this is the correct solution for calling something via FFI (for which there don't seem to be any better results on Google).

Related

Rust: Convert a mutable u8 pointer to a mutable reference

How can I convert a mutable u8 pointer to a mutable reference of another type?
let ptr: *mut u8;
let reference: &mut SomeType = ?; // What should i do here?
I have found a sort-of viable solution, but I wonder if there is a better way:
let reference = unsafe { &mut *(ptr as *mut SomeType) };
You have already found an acceptable method. A slightly preferable one is to use pointer::cast instead of as, because that explicitly specifies that you are trying to change the type of the referent and not any of the many other things as can do.
let ptr = ptr.cast::<SomeType>();
let reference = unsafe { &mut *ptr };
Do not use std::mem::transmute for this. Transmuting should always be the last resort in any circumstance (the nomicon and function documentation say so!), because it reinterprets the bytes regardless of what they are — in this case it'll convert any pointer-sized value, such as a reference to the pointer. By sticking with cast and &*, we catch more possible type errors. (Clippy even has a default lint against using transmute here.)
You could use std::mem::transmute instead:
use std::mem::transmute;
#[repr(transparent)]
struct SomeStruct(u8);
fn main() {
let a = &mut 10u8;
let ptr = a as *mut u8;
let reference: &mut SomeStruct = unsafe { transmute(ptr) };
}

Does casting pointers in Rust have the same behavior as reinterpret_cast in C++?

I have this struct defined in my code:
#[repr(align(4))]
struct MetaDataDefn {
cncVersion: i32,
toDriverBufferLength: i32,
toClientsBufferLength: i32,
counterMetadataBufferLength: i32,
counterValuesBuferLength: i32,
clientLivenessTimeout: i64,
startTimestamp: i64,
pid: i64
}
I have a function that takes a raw pointer to a chunk of memory, where the first bytes correspond to a struct with the same layout.
I thought that if I cast the u8 pointer to a struct pointer, I'd get the same result as if I did a reinterpret_cast in C++. However, I think that's not the case, and I'm a bit confused about what's going on here. This is the body of the function (the pointer that the function receives is cncFilePtr):
let metadata = unsafe { cncFilePtr as *mut MetaDataDefn };
// This works
let cncVersion = unsafe { (*(cncFilePtr as *mut i32)) };
println!("CNC Version: {}", cncVersion);
//This prints a different number than the previous code
println!("CNC version (other way): {}", unsafe { (*metadata).cncVersion });
As you can see, casting the first 4 bytes to a i32 and then printing the result gives a different result than casting the whole thing to MetaDataDefn and accessing the first member, which is of type i32 (my understanding is that both approaches should give the same result)
My question is: why it's not the same result? is casting pointers in Rust not the same as reinterpret_cast in C++ (I come from a C++ background)?
Normally, Rust makes no guarantees about the way that a struct is represented in memory. It can reorder fields to make them pack more tightly, and could theoretically even optimise the field order based on how your application actually accesses them.
You can fix the order, to behave like C, by adding the #[repr(C)] attribute:
#[repr(C)]
#[repr(align(4))]
struct MetaDataDefn { ... }
With that, both pointers will give the same result because this guarantees that cncVersion appears first.

How do I make the equivalent of a C double pointer in Rust?

I started porting C code to Rust, but I'm confused about how things work in Rust. What is the equivalent of this code:
typedef struct Room {
int xPos;
int yPos;
} Room;
void main (){
Room **rooms;
rooms = malloc(sizeof(Room)*8);
}
What is the equivalent of this code
Assuming you mean "a collection of Rooms with capacity for 8":
struct Room {
x_pos: i32,
y_pos: i32,
}
fn main() {
let rooms: Vec<Room> = Vec::with_capacity(8);
}
It's exceedingly rare to call the allocator directly in Rust. Generally, you have a collection that does that for you. You also don't usually explicitly specify the item type of the collection because it can be inferred by what you put in it, but since your code doesn't use rooms at all, we have to inform the compiler.
As pointed out in the comments, you don't need a double pointer. This is the equivalent of a Room *. If you really wanted an additional level of indirection, you could add Box:
let rooms: Vec<Box<Room>> = Vec::with_capacity(8);
How do I make the equivalent of a C double pointer
One of the benefits of Rust vs C is that in C, you don't know the semantics of a foo_t **. Who should free each of the pointers? Which pointers are mutable? You can create raw pointers in Rust, but even that requires specifying mutability. This is almost never what you want:
let rooms: *mut *mut Room;
In certain FFI cases, a C function accepts a foo_t ** because it wants to modify a passed-in pointer. In those cases, something like this is reasonable:
unsafe {
let mut room: *mut Room = std::ptr::null_mut();
let room_ptr: *mut *mut Room = &mut room;
}

Pointer to trait

When I started learning Rust, I naively assumed Rust's pointers to traits were implemented just like a C++ pointer to a base class, and wrote some code that worked even under that assumption. Specifically, the code I wrote interfaced with an FFI library that needed to read and seek a stream, and it was something like this:
struct StreamParts {
reader: *mut Read,
seeker: *mut Seek,
}
fn new_ffi_object<T: Read + Seek + 'static>(stream: T) -> FFIObject {
let stream_ptr = Box::into_raw(Box::new(stream));
let stream_parts = Box::into_raw(Box::new(StreamParts {
reader: stream_ptr as *mut Read,
seeker: stream_ptr as *mut Seek,
}));
ffi_library::new_object(stream_parts, ffi_read, ffi_seek, ffi_close)
}
extern "C" fn ffi_read(stream_parts: *mut StreamParts, ...) -> c_ulong {
(*stream_parts.reader).read(...)
...
}
extern "C" fn ffi_seek(stream_parts: *mut StreamParts, ...) -> c_ulong {
(*stream_parts.seeker).seek(...)
...
}
extern "C" fn ffi_close(stream_parts: *mut StreamParts) {
mem::drop(Box::from_raw(stream_parts.reader));
mem::drop(Box::from_raw(stream_parts));
}
And it worked. However, there are three things I don't fully understand about why it works:
Rust's trait objects are fat, containing two pointers. Thus, unlike C++, *mut Read is a pointer to a trait object, correct? And where is this trait object allocated? The Rust docs don't touch on this specific case.
Am I correct to assume that mem::drop(Box::from_raw(stream_parts.reader)) fully drops the original stream?
Why is the 'static needed in new_ffi_object()?
Pointers and references behave exactly the same, except for the borrow-checker which forbids you to have dangling references and the fact that you need to wrap pointer dereferencing into an unsafe block.
So yes, sizeof::<*mut Read>() == sizeof::<*mut ()>() * 2. The trait object isn't allocated anywhere. It's nothing more than a struct with two fields. One that is a pointer that points to your data, and one that is a pointer that points to the vtable. The vtable is allocated in the static memory.
Correct. It accesses the vtable pointer of reader and looks up the drop impl in the vtable.
If you didn't have a 'static lifetime, your T might contain references with lifetimes shorter than 'static. All that lifetime bound says is that T doesn't have such references and may thus be copied anywhere without restrictions, even on the heap.

How does Rust know which types own resources?

When one has a box pointer to some heap-allocated memory, I assume that Rust has 'hardcoded' knowledge of ownership, so that when ownership is transferred by calling some function, the resources are moved and the argument in the function is the new owner.
However, how does this happen for vectors for example? They too 'own' their resources, and ownership mechanics apply like for box pointers -- yet they are regular values stored in variables themselves, and not pointers. How does Rust (know to) apply ownership mechanics in this situation?
Can I make my own type which owns resources?
tl;dr: "owning" types in Rust are not some magic and they are most certainly not hardcoded into the compiler or language. They are just types which written in a certain way (do not implement Copy and likely have a destructor) and have certain semantics which is enforced through non-copyability and the destructor.
In its core Rust's ownership mechanism is very simple and has very simple rules.
First of all, let's define what move is. It is simple - a value is said to be moved when it becomes available under a new name and stops being available under the old name:
struct X(u32);
let x1 = X(12);
let x2 = x1;
// x1 is no longer accessible here, trying to use it will cause a compiler error
Same thing happens when you pass a value into a function:
fn do_something(x: X) {}
let x1 = X(12);
do_something(x1);
// x1 is no longer accessible here
Note that there is absolutely no magic here - it is just that by default every value of every type behaves like in the above examples. Values of each struct or enum you or someone else creates by default will be moved.
Another important thing is that you can give every type a destructor, that is, a piece of code which is invoked when the value of this type goes out of scope and destroyed. For example, destructors associated with Vec or Box will free the corresponding piece of memory. Destructors can be declared by implementing Drop trait:
struct X(u32);
impl Drop for X {
fn drop(&mut self) {
println!("Dropping {}", x.0);
}
}
{
let x1 = X(12);
} // x1 is dropped here, and "Dropping 12" will be printed
There is a way to opt-out of non-copyability by implementing Copy trait which marks the type as automatically copyable - its values will no longer be moved but copied:
#[derive(Copy, Clone)] struct X(u32);
let x1 = X(12);
let x2 = x1;
// x1 is still available here
The copy is done bytewise - x2 will contain a byte-identical copy of x1.
Not every type can be made Copy - only those which have Copy interior and do not implement Drop. All primitive types (except &mut references but including *const and *mut raw pointers) are Copy in Rust, so each struct which contains only primitives can be made Copy. On the other hand, structs like Vec or Box are not Copy - they deliberately do not implement it because bytewise copy of them will lead to double frees because their destructors can be run twice over the same pointer.
The Copy bit above is a slight digression on my side, just to give a clearer picture. Ownership in Rust is based on move semantics. When we say that some value own something, like in "Box<T> owns the given T", we mean semantic connection between them, not something magical or something which is built into the language. It is just most such values like Vec or Box do not implement Copy and thus moved instead of copied, and they also (optionally) have a destructor which cleans up anything these types may have allocated for them (memory, sockets, files, etc.).
Given the above, of course you can write your own "owning" types. This is one of the cornerstones of idiomatic Rust, and a lot of code in the standard library and external libraries is written in such way. For example, some C APIs provide functions for creating and destroying objects. Writing an "owning" wrapper around them is very easy in Rust and it is probably very close to what you're asking for:
extern {
fn create_widget() -> *mut WidgetStruct;
fn destroy_widget(w: *mut WidgetStruct);
fn use_widget(w: *mut WidgetStruct) -> u32;
}
struct Widget(*mut WidgetStruct);
impl Drop for Widget {
fn drop(&mut self) {
unsafe { destroy_widget(self.0); }
}
}
impl Widget {
fn new() -> Widget { Widget(unsafe { create_widget() }) }
fn use_it(&mut self) -> u32 {
unsafe { use_widget(self.0) }
}
}
Now you can say that Widget owns some foreign resource represented by *mut WidgetStruct.
Here is another example of how a value might own memory and free it when the value is destroyed:
extern crate libc;
use libc::{malloc, free, c_void};
struct OwnerOfMemory {
ptr: *mut c_void
}
impl OwnerOfMemory {
fn new() -> OwnerOfMemory {
OwnerOfMemory {
ptr: unsafe { malloc(128) }
}
}
}
impl Drop for OwnerOfMemory {
fn drop(&mut self) {
unsafe { free(self.ptr); }
}
}
fn main() {
let value = OwnerOfMemory::new();
}

Resources