-
Notifications
You must be signed in to change notification settings - Fork 10
Creating your own loader
Let's create a custom loader to load C files.
-
Create a new file called
cLoader.ts
. -
Inside it, we'll extend the Loader class and add our configuration to it.
import { Loader } from "hyperimport"; import { basename, parse } from "path"; export default class extends Loader { constructor() { super("C Loader", { extension: "c", buildCommand: (importPath, outDir) => [ "gcc", "-shared", "-fpic", importPath, "-o", `${outDir}/lib${parse(importPath).name}.so` ], outDir: importPath => `build/${basename(importPath)}` } ); } };
-
Add the file path to
custom
in hyperimport config inside bunfig.toml.[hyperimport] custom = ["./cLoader.ts"]
-
Create a new C file called
math.c
. -
Inside it, we'll write a simple function to add two integers.
int math(int a, int b) { return a + b; }
-
Inside index.ts, import the math function from
math.c
.import { math } from "./math.c"; console.log(math(10, 5));
You'll see the typescript error
Cannot find module
when importing that, don't worry, it gets fixed in the next steps. -
Now simply run
bun .
to execute index.ts. -
You'll see something like,
[HYPERIMPORT]: C Loader No configuration was found for "/hypertest/math.c" Enter the build command and output directory to configure it. Press enter to use the default values. build command: (default)
It means, hyperimport successfully registered our custom "C Loader" we created earlier.
-
Press enter to go with the default values.
-
Now you'll see something like,
Config file has been generated at "/hypertest/@types/math.c/config.ts" Edit the config.ts and set the argument and return types, then rerun the script.
-
Navigate to the newly created file
@types/math.c/config.ts
. -
Inside you'll find the configuration to load math.c. Add the argument and return types for the math function.
math: { args: [T.int, T.int], returns: T.int }
This tells FFI that, the
math
function takes twoint
s as arguments and returns anint
as a result. -
At this step, you'll notice the typescript error we got earlier is now resolved and if you hover over the
math
function, you'll find it is now properly typed. -
For the final step, run
bun .
again to rerun the script. -
10
is successfully logged into the console as it should. -
To check auto reloading, go back to
math.c
. -
Change the
+
to-
. -
Run
bun .
again. -
Hyperimport automatically rebuilds the changed code and logs
5
into the console.