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

Support napi inside of bun:ffi #14028

Merged
merged 2 commits into from
Sep 19, 2024
Merged

Support napi inside of bun:ffi #14028

merged 2 commits into from
Sep 19, 2024

Conversation

Jarred-Sumner
Copy link
Collaborator

@Jarred-Sumner Jarred-Sumner commented Sep 19, 2024

What does this PR do?

This makes it easier to return strings from bun:ffi to JavaScript, by allowing you to go through the napi code path to do so.

Example C:

#include <node/node_api.h>

napi_value napi(napi_env env) {
  napi_value result;
  napi_create_string_utf8(env, "Hello, Napi!", NAPI_AUTO_LENGTH, &result);
  return result;
}

JS usage:

import { cc } from "bun:ffi";
import source from "./hello-napi.c" with { type: "file" };
const {
  symbols: { napi },
} = cc({
  source,
  symbols: {
    "napi": {
      args: ["napi_env"],
      returns: "napi_value",
    },
  },
});

if (napi() !== "Hello, Napi!") {
  throw new Error("napi() !== Hello, Napi!");
}

How did you verify your code works?

Updated a test

@@ -19,3 +23,7 @@ const {
if (main() !== 42) {
throw new Error("main() !== 42");
}

if (napi_main(null) !== "Hello, Napi!") {
Copy link
Collaborator

Choose a reason for hiding this comment

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

is this going to segfault in the handle scope code?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

discussed IRL

@Jarred-Sumner Jarred-Sumner merged commit 6415296 into main Sep 19, 2024
45 of 46 checks passed
@Jarred-Sumner Jarred-Sumner deleted the jarred/napi-in-ffi branch September 19, 2024 10:19
@codehz
Copy link
Contributor

codehz commented Sep 19, 2024

is it possible to receive argument via napi?
I mean the "napi_callback_info"

https://www.npmjs.com/package/bigint-buffer <- a 281562 weekly download library is just used for convert between bigint and buffer
and the source code is here: https://github.com/no2chem/bigint-buffer/blob/master/src/bigint-buffer.c

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.

4 participants