2021-07-01 17:23:16 +08:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2020-2021 Thakee Nathees
|
|
|
|
* Distributed Under The MIT License
|
|
|
|
*/
|
|
|
|
|
|
|
|
// This is a minimal example on how to pass values between pocket VM and C.
|
|
|
|
|
|
|
|
#include <pocketlang.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
// The pocket script we're using to test.
|
|
|
|
static const char* code =
|
2022-04-22 00:07:38 +08:00
|
|
|
" from my_module import cFunction \n"
|
|
|
|
" a = 42 \n"
|
|
|
|
" b = cFunction(a) \n"
|
|
|
|
" print('[pocket] b = $b') \n"
|
2021-07-01 17:23:16 +08:00
|
|
|
;
|
|
|
|
|
|
|
|
/*****************************************************************************/
|
|
|
|
/* MODULE FUNCTION */
|
|
|
|
/*****************************************************************************/
|
|
|
|
|
2022-04-22 00:07:38 +08:00
|
|
|
static void cFunction(PKVM* vm) {
|
2021-07-01 17:23:16 +08:00
|
|
|
|
|
|
|
// Get the parameter from pocket VM.
|
|
|
|
double a;
|
2022-04-23 10:30:49 +08:00
|
|
|
if (!pkValidateSlotNumber(vm, 1, &a)) return;
|
2021-07-01 17:23:16 +08:00
|
|
|
|
|
|
|
printf("[C] a = %f\n", a);
|
|
|
|
|
|
|
|
// Return value to the pocket VM.
|
2022-04-23 10:30:49 +08:00
|
|
|
pkSetSlotNumber(vm, 0, 3.14);
|
2021-07-01 17:23:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/*****************************************************************************/
|
|
|
|
/* POCKET VM CALLBACKS */
|
|
|
|
/*****************************************************************************/
|
|
|
|
|
2022-04-22 00:07:38 +08:00
|
|
|
static void stdoutCallback(PKVM* vm, const char* text) {
|
2021-07-01 17:23:16 +08:00
|
|
|
fprintf(stdout, "%s", text);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*****************************************************************************/
|
|
|
|
/* MAIN */
|
|
|
|
/*****************************************************************************/
|
|
|
|
|
|
|
|
int main(int argc, char** argv) {
|
|
|
|
|
|
|
|
// Pocket VM configuration.
|
|
|
|
PkConfiguration config = pkNewConfiguration();
|
2022-04-22 20:21:17 +08:00
|
|
|
config.stdout_write = stdoutCallback;
|
2021-07-01 17:23:16 +08:00
|
|
|
|
|
|
|
// Create a new pocket VM.
|
|
|
|
PKVM* vm = pkNewVM(&config);
|
|
|
|
|
2022-04-22 00:07:38 +08:00
|
|
|
// Registering a native module.
|
|
|
|
PkHandle* my_module = pkNewModule(vm, "my_module");
|
|
|
|
pkModuleAddFunction(vm, my_module, "cFunction", cFunction, 1);
|
|
|
|
pkRegisterModule(vm, my_module);
|
|
|
|
pkReleaseHandle(vm, my_module);
|
2021-07-01 17:23:16 +08:00
|
|
|
|
|
|
|
// The path and the source code.
|
2022-04-22 00:07:38 +08:00
|
|
|
PkStringPtr source = { .string = code };
|
|
|
|
PkStringPtr path = { .string = "./some/path/" };
|
2021-07-01 17:23:16 +08:00
|
|
|
|
|
|
|
// Run the code.
|
|
|
|
PkResult result = pkInterpretSource(vm, source, path, NULL/*options*/);
|
|
|
|
|
|
|
|
// Free the VM.
|
|
|
|
pkFreeVM(vm);
|
|
|
|
|
|
|
|
return (int)result;
|
|
|
|
}
|