Skip to content

Instantly share code, notes, and snippets.

@preble
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save preble/9ec10d7157c0445a463d to your computer and use it in GitHub Desktop.
Save preble/9ec10d7157c0445a463d to your computer and use it in GitHub Desktop.
Demonstration of calling a Wren method from the current embedding API. More on Wren: http://wren.io/ Derived from: https://github.com/munificent/wren/issues/194
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include "wren.h"
void logFromWren(WrenVM *vm) {
//double x = wrenGetArgumentDouble(vm, 0); // returns 0 in this setting
const char *message = wrenGetArgumentString(vm, 1);
printf("logFromWren: %s\n", message);
}
WrenForeignMethodFn bindForeignMethod(WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) {
if (strcmp(module, "main") == 0
&& strcmp(className, "Interface") == 0
&& strcmp(signature, "log(_)") == 0) {
return logFromWren;
}
return NULL;
}
void demo_foreign() {
WrenConfiguration config = { 0 };
config.bindForeignMethodFn = bindForeignMethod;
WrenVM *vm = wrenNewVM(&config);
const char wrenSource[] = ""
"var Counter = 0 \n"
"class Interface { \n"
" static say(text) { \n"
" Counter = Counter + 1 \n"
" IO.print(\"Interface.say() called with: \", text, \" Counter = \", Counter) \n"
" log(\"Hello from Wren!\") \n"
" } \n"
" foreign static log(message) \n"
"} \n";
WrenInterpretResult result = wrenInterpret(vm, "dummy.wren", wrenSource);
assert(result == WREN_RESULT_SUCCESS);
WrenMethod *method = wrenGetMethod(vm, "main", "Interface", "say(_)");
wrenCall(vm, method, "s", "Howdy!");
wrenCall(vm, method, "s", "Again!");
wrenReleaseMethod(vm, method);
wrenFreeVM(vm);
}
#include <assert.h>
#include "wren.h"
void demo_method_call() {
WrenConfiguration config = { 0 };
WrenVM *vm = wrenNewVM(&config);
const char wrenSource[] = ""
"class Foo { \n"
" static say(text) { \n"
" IO.print(\"Foo.say() called with: \", text) \n"
" } \n"
"}";
WrenInterpretResult result = wrenInterpret(vm, "dummy.wren", wrenSource);
assert(result == WREN_RESULT_SUCCESS);
WrenMethod *method = wrenGetMethod(vm, "main", "Foo", "say(_)");
wrenCall(vm, method, "s", "Howdy!"); // "Foo.say() called with: Howdy!"
wrenReleaseMethod(vm, method);
wrenFreeVM(vm);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment