Skip to content

chore(napi): expose functions which turn raw pointer into External#2449

Merged
Brooooooklyn merged 2 commits intonapi-rs:mainfrom
zackradisic:expose-tagged-object
Feb 3, 2025
Merged

chore(napi): expose functions which turn raw pointer into External#2449
Brooooooklyn merged 2 commits intonapi-rs:mainfrom
zackradisic:expose-tagged-object

Conversation

@zackradisic
Copy link
Copy Markdown
Contributor

Hi, we recently shipped a native bundler plugin API for Bun, with a Rust crate which exposes a convenient way to create native bundler plugins for Bun (here).

Native bundler plugins in Bun are NAPI modules which expose an additional symbol to a function which implements the bundler plugin code.

To make this nicer to write in Rust, we want to allow users to integrate it with napi-rs.

We want to allow users to use napi-rs External type when writing native bundler plugins. Native bundler plugins can carry around the raw pointer to the napi external.

However, napi-rs does not mark the fields of External as pub or export anyway to go from *mut c_void -> External<T>.

Currently in bun-native-plugin-rs we do something like this to do that:

/// Copy-pasted from napi-rs, not ideal
#[repr(C)]
pub struct TaggedObject<T> {
    type_id: TypeId,
    pub(crate) object: Option<T>,
}

pub unsafe fn external<T: 'static + Sync>(&self) -> PluginResult<Option<&'static T>> {

        // ...
        
        let external: *mut TaggedObject<T> =
            unsafe { (*self.args_raw).external as *mut TaggedObject<T> };
            
         // ...
}

This is obviously bad as napi-rs could change TaggedObject.

So this PR exports function which exposes some logic to go from *mut c_void -> Option<&T>, where T is the inner type of the External<T>.

@Brooooooklyn Brooooooklyn changed the title Expose functions which turn raw pointer into External chore(napi): expose functions which turn raw pointer into External Feb 3, 2025
Copy link
Copy Markdown
Member

@Brooooooklyn Brooooooklyn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@Brooooooklyn Brooooooklyn merged commit 2d8e19d into napi-rs:main Feb 3, 2025
Brooooooklyn pushed a commit that referenced this pull request Feb 3, 2025
…2449)

* Expose functions which turn raw pointer into External

* Add safety documentation
@Brooooooklyn
Copy link
Copy Markdown
Member

@zackradisic released in https://github.com/napi-rs/napi-rs/releases/tag/napi%402.16.14

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

Successfully merging this pull request may close these issues.

2 participants