Created
May 4, 2017 19:29
-
-
Save kungfooman/e42b4015aab2f2be9c3f93d183aa942e to your computer and use it in GitHub Desktop.
global test
This file contains 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 <stdio.h> | |
#include "duktape.h" | |
duk_ret_t duk_func_log(duk_context *ctx) { | |
int i; | |
int n = duk_get_top(ctx); /* #args */ | |
char *res; | |
for (i = 0; i < n; i++) { | |
res = (char *)duk_to_string(ctx, i); | |
printf("%s", res); | |
} | |
return 0; | |
} | |
int js_register_function(duk_context *ctx, char *name, int (*func)(duk_context *ctx)) { | |
duk_push_c_function(ctx, func, DUK_VARARGS); | |
duk_put_global_string(ctx, name); | |
return 1; | |
} | |
int js_push_global_by_name(duk_context *ctx, char *name) { | |
// [..., global] | |
duk_push_global_object(ctx); | |
// [..., global, prop || undefined] | |
int function_exists = duk_get_prop_string(ctx, -1, name); | |
// [..., prop || undefined] | |
duk_remove(ctx, -2); | |
return function_exists; | |
} | |
int main() { | |
duk_context *ctx = duk_create_heap_default(); | |
js_register_function(ctx, "log", duk_func_log); | |
duk_eval_string(ctx, "str = 'abc\\n'; function callme() { log(str); }"); | |
duk_pop(ctx); | |
//duk_eval_string(ctx, "callme();"); | |
//duk_pop(ctx); | |
js_push_global_by_name(ctx, "callme"); | |
int rc = duk_pcall(ctx, 0); | |
duk_pop(ctx); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment