Last active
August 17, 2021 09:58
-
-
Save subsetpark/d4d278f27fff90a3ea1b8064bb169284 to your computer and use it in GitHub Desktop.
baby's first Janet C module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <janet.h> | |
// Function to be exported | |
// Returns a Janet; that's the static value that boxes a dynamic Janet type | |
// argc: number of arguments it was called with | |
// argv: arguments array | |
static Janet interp(int32_t argc, Janet *argv) { | |
// Assert that argc == 2 | |
janet_fixarity(argc, 2); | |
// getting variables from argument array; using janet_get* functions | |
const uint8_t *s1 = janet_getstring(argv, 0); | |
const uint8_t *s2 = janet_getstring(argv, 1); | |
// business logic | |
int s1_length = janet_string_length(s1); | |
int s2_length = janet_string_length(s2); | |
int32_t strlength = s1_length + s2_length; | |
// janet_smalloc - just like normal malloc (allocate memory), but this memory | |
// will be garbage collected | |
// | |
// trivia: to allocate on the stack, this would be | |
// char newstring[strlength]; | |
// and we wouldn't call `janet_sfree` below. | |
// this is called 'variable length arrays' and I didn't know it was possible | |
char *newstring = janet_smalloc(strlength); | |
int i; | |
for (i = 0; i < s1_length; i++) { | |
newstring[i] = s1[i]; | |
} | |
for (i = 0; i < s2_length; i++) { | |
newstring[i + s1_length] = s2[i]; | |
} | |
// janet_cstring: C string -> JanetString; | |
// the type signature of `janet_string`'s first parameter is `const | |
// uint8_t`. newstring is currently a `char`; but we can cast it in | |
// this call because we know it won't be changed. | |
JanetString res = janet_string((const uint8_t *)newstring, strlength); | |
// Free the allocated memory, because we allocated some new memory to | |
// create the JanetString | |
janet_sfree(newstring); | |
// janet_wrap_string: JanetString -> Janet; | |
return janet_wrap_string(res); | |
} | |
// Function registry | |
static const JanetReg cfuns[] = {{"interp", interp, "(foo bar) docstring."}, | |
{NULL, NULL, NULL}}; | |
JANET_MODULE_ENTRY(JanetTable *env) { janet_cfuns(env, "custom-mod", cfuns); } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment