Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Figure out how to get rid of 'unsafe'. #7

Open
floooh opened this issue Mar 30, 2023 · 2 comments
Open

Figure out how to get rid of 'unsafe'. #7

floooh opened this issue Mar 30, 2023 · 2 comments

Comments

@floooh
Copy link
Owner

floooh commented Mar 30, 2023

The examples have quite a few unsafe in them. Would be nice if the sokol-bindings would allow to write code without usafe.

Maybe having separate internal C-compatible structs and public 'Rust-y' structs like I mentioned here (#6) could be the solution?

@floooh floooh changed the title Figure out how to get rid of the unsafe wrapper. Figure out how to get rid of 'unsafe'. Mar 30, 2023
@EriKWDev
Copy link
Contributor

EriKWDev commented Apr 2, 2023

Yes, there are some places where unsafe is needed currently.

The main one is whenever you want to convert a C-style pointer into a rust reference, we need to dereference it which in rust is unsafe for C pointers since they "could be null".

This includes *const sapp::EventType, *mut core::ffi::c_void userdata for all callbacks.

One thing I thogh about was making all the userdata related functions that return a *mut core::ffi::c_void instead be generic over a type T and return a mutable reference to that T.

This could look as such:

fn userdata<T>() -> &mut T {
    unsafe { std::mem::transmute(ffi::userdata() as *mut T) }
}


// At call-site no unsafe needed, just explicit type required 

let state: &mut MyStateStruct = sapp::userdata();

I'll have to think about if that transmute is valid. I'm not at a computer atm but I believe if we simply dereference the pointer and cast it normally to a reference we will get lifetime issues when we return it, but that might be incorrect.

The other places where unsafe is used are where I chose to use a global variable for the state instead of passing it as userdata. Getting a mutable reference to global data in Rust is considered unsafe always and is not related to the sokol bindings.

@floooh
Copy link
Owner Author

floooh commented May 20, 2024

As a reminder, see comments here:

#26

...and here:

#30

...maybe the fix to avoid global state (and instead pass heap-allocated state into callbacks via the user_data pointer) can be wrapped in some sort of SokolApp helper "class" which contains the "unsafety".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants