aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md50
-rw-r--r--src/bun.js/ffi.exports.js2
2 files changed, 20 insertions, 32 deletions
diff --git a/README.md b/README.md
index bec00eed3..6996c31d7 100644
--- a/README.md
+++ b/README.md
@@ -3835,41 +3835,32 @@ Bun v0.2.3 added `JSCallback` which lets you create JavaScript callback function
import { dlopen, JSCallback } from "bun:ffi";
const {
- symbols: { setOnResolve, setOnReject },
+ symbols: { search },
+ close,
} = dlopen("libmylib", {
- setOnResolve: {
- returns: "bool",
- args: ["function"],
- },
- setOnReject: {
- returns: "bool",
- args: ["function"],
+ search: {
+ returns: "usize",
+ args: ["cstring", "callback"],
},
});
-const onResolve = new JSCallback(
+const searchIterator = new JSCallback(
+ (ptr, length) => Buffer.from(ptr, length, "utf8").toString().test(/wut/i),
{
returns: "bool",
- args: ["i32"],
- },
- (arg) => arg === 42
-);
-
-const onReject = new JSCallback(
- {
- returns: "bool",
- args: ["i32"],
- },
- (arg) => arg > 42
+ args: ["ptr", "usize"],
+ }
);
-setOnResolve(onResolve);
-setOnReject(onReject);
+const str = Buffer.from("wwutwutwutwutwutwutwutwutwutwutut\0", "utf8");
+if (search(ptr(str), searchIterator)) {
+ // found a match!
+}
// Sometime later:
setTimeout(() => {
- onResolve.close();
- onReject.close();
+ searchIterator.close();
+ close();
}, 5000);
```
@@ -3878,13 +3869,10 @@ When you're done with a JSCallback, you should call `close()` to free the memory
For a slight performance boost, directly pass `JSCallback.prototype.ptr` instead of the `JSCallback` object:
```ts
-const onResolve = new JSCallback(
- {
- returns: "bool",
- args: ["i32"],
- },
- (arg) => arg === 42
-);
+const onResolve = new JSCallback((arg) => arg === 42, {
+ returns: "bool",
+ args: ["i32"],
+});
const setOnResolve = new CFunction({
returns: "bool",
args: ["function"],
diff --git a/src/bun.js/ffi.exports.js b/src/bun.js/ffi.exports.js
index faf74d1b8..68876bb6f 100644
--- a/src/bun.js/ffi.exports.js
+++ b/src/bun.js/ffi.exports.js
@@ -16,7 +16,7 @@ delete ffi.callback;
delete ffi.closeCallback;
export class JSCallback {
- constructor(options, cb) {
+ constructor(cb, options) {
const { ctx, ptr } = nativeCallback(options, cb);
this.#ctx = ctx;
this.ptr = ptr;