SSheldon / rust-objc

Objective-C Runtime bindings and wrapper for Rust.
https://crates.io/crates/objc
MIT License
388 stars 56 forks source link

Example of how to encode a String from a NSString? #82

Closed seanvoss closed 4 years ago

seanvoss commented 5 years ago

Hi, I've been able to implement a action for a textField and I am working on retrieving the NSString representation, but so far I've been unable to figure out the sequence of events to extract that into a Rust String.

seanvoss commented 5 years ago

Figured out a way, perhaps with some cleanup there might be a path to including in the library as I imagine it's a path that lots of projects would need.

                    let window: &mut Object = msg_send!(foo, window);
                    let responder: &mut Object = msg_send!(window, firstResponder);
                    let text: &mut Object  = msg_send!(responder, string);
                    let text =  msg_send!(text, cString);
                    let c_str = str::from_utf8_unchecked(slice::from_raw_parts(text as *const u8, strlen(text)));
SSheldon commented 4 years ago

@seanvoss glad you got it figured out!

This crate doesn't include anything specific to the objc Foundation framework (which is where things like NSString, NSArray, etc come from). There's the objc-foundation crate for things like that, but I'm not really focusing on improving or expanding it anymore. (It turns out trying to represent an Objective-C framework in safe rust is a ton of work.)

If it's ever helpful, here's how that crate handles getting a &str from an NSString: https://github.com/SSheldon/rust-objc-foundation/blob/0.1.1/src/string.rs#L52-L61