Brendonovich / swift-rs

Call Swift functions from Rust with ease!
Apache License 2.0
259 stars 30 forks source link

Allow for wrapping a block of code under an autoreleasepool #18

Closed amodm closed 1 year ago

amodm commented 1 year ago

Following up from my comment in #8, please consider providing an easy macro to wrap a block of code under an autoreleasepool.

Copy pasting my proposal earlier in that thread, something like this can work:

#[macro_export]
macro_rules! autoreleasepool {
    ( $expr:expr ) => {{
        extern "C" {
            fn objc_autoreleasePoolPush() -> *mut std::ffi::c_void;
            fn objc_autoreleasePoolPop(context: *mut std::ffi::c_void);
        }

        let pool = unsafe { objc_autoreleasePoolPush() };
        let r = { $expr };
        unsafe { objc_autoreleasePoolPop(pool) };
        r
    }};
}

This would allow devs to wrap the right amount of code, as deemed appropriate by them, under an autoreleasepool, e.g.

autoreleasepool!({
    for _ in 0..1000 {
        // do something a 1000 times
    }
});

This would greatly help with memory profile of codebases that use legacy objc code (directly or indirectly).

amodm commented 1 year ago

If the proposal works for you, I can push a PR. Alternatively, you figuring out a better model for this, works too.

Brendonovich commented 1 year ago

@amodm I'm cool with this, feel free to PR it!