pocketlang/tests/native/example1.c

57 lines
1.6 KiB
C
Raw Normal View History

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>
// 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;
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.
pkSetSlotNumber(vm, 0, 3.14);
2021-07-01 17:23:16 +08:00
}
/*****************************************************************************/
/* MAIN */
/*****************************************************************************/
int main(int argc, char** argv) {
// Create a new pocket VM.
2022-05-04 14:28:23 +08:00
PKVM* vm = pkNewVM(NULL);
2021-07-01 17:23:16 +08:00
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
// Run the code.
2022-05-04 14:28:23 +08:00
PkResult result = pkRunString(vm, code);
2021-07-01 17:23:16 +08:00
// Free the VM.
pkFreeVM(vm);
2022-05-04 14:28:23 +08:00
return (int) result;
2021-07-01 17:23:16 +08:00
}