Skip to content

Instantly share code, notes, and snippets.

@wille-io
Last active May 18, 2018 13:54
Show Gist options
  • Select an option

  • Save wille-io/0b49e7de90392de3260e6e2d769ad60a to your computer and use it in GitHub Desktop.

Select an option

Save wille-io/0b49e7de90392de3260e6e2d769ad60a to your computer and use it in GitHub Desktop.
jerryscript: Call to a JavaScript function from a prototype of 'this' when external function was called
#include <string.h>
#include <stdio.h>
#include <jerryscript.h>
#include <jerryscript-ext/handler.h>
static jerry_value_t c_function_handler(const jerry_value_t function_obj,
const jerry_value_t this_val,
const jerry_value_t args_p[],
const jerry_length_t args_cnt)
{
jerry_value_t prototype = jerry_get_prototype(this_val);
jerry_value_t prop_name = jerry_create_string((const jerry_char_t *)"x");
jerry_value_t receive_function = jerry_get_property(prototype, prop_name);
if (!jerry_value_is_function(receive_function))
{
puts("not a function :(");
return jerry_create_boolean(false);
}
jerry_call_function(receive_function, jerry_create_undefined(), 0, 0);//args, argc);
return jerry_create_boolean(true);
}
int main()
{
jerry_init(JERRY_INIT_EMPTY);
const char *script =
" function Test() "
" { "
" c_function(this); "
" } "
" "
" Test.prototype.x = function() "
" { "
" print('SUCCESS!'); "
" }; "
" "
" function go() "
" { "
" var x = new Test(); "
" } "
" "
" go(); ";
jerry_value_t parsed_code = jerry_parse(0, 0, (jerry_char_t *)script, strlen(script), JERRY_PARSE_NO_OPTS);
jerry_value_t glob_obj = jerry_get_global_object();
jerry_value_t prop_name = jerry_create_string((const jerry_char_t *)"c_function");
jerry_value_t func_val = jerry_create_external_function(c_function_handler);
jerry_set_property(glob_obj, prop_name, func_val);
jerryx_handler_register_global((const jerry_char_t *)"print", jerryx_handler_print);
if (!jerry_value_is_error(parsed_code))
{
jerry_value_t ret_value = jerry_run(parsed_code);
jerry_release_value(ret_value);
}
else
{
puts("error!");
jerry_error_t err = jerry_get_error_type(parsed_code);
printf("type: %d\n", err);
}
jerry_cleanup();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment