jerryscript icon indicating copy to clipboard operation
jerryscript copied to clipboard

A little confused about JS calling c ++

Open hellozimo opened this issue 9 years ago • 9 comments

Is there a simple example about JS calling c ++?

How to call c ++ member functions in js file?

hellozimo avatar Nov 29 '17 02:11 hellozimo

@zhaojuntao did you check http://jerryscript.net/api-example/?

LaszloLango avatar Nov 29 '17 08:11 LaszloLango

@LaszloLango
I have read all documents, but have not found how to call c ++ member functions in js file intuitively.
Fllows are test codes, By referencing other people's code. Major steps:

  • Rewrap c ++ functions by C function
  • create new object and add it to global object ( Is it necessary? )
  • set native founction pointer

I am not sure if the fllows code by mentioned above is reasonable.
Please give me some advice, thanks.

hello.cpp

#include "hello.h"

hello::hello ()
{
    printf("\n print in hello() function! \n");
}

hello::hello (int id)
{
    printf("\n print in hello(int id) function, id = %d \n", id);
}

hello::~hello ()
{

}

void hello::hello_param(void)
{
    printf("\n print in hello_param() function! \n");
}

void hello::hello_param(int id)
{
    printf("\n print in hello_param(int id) function, id = %d \n", id);
}

main.js

function sysloop (ticknow)
{
  print ("in main.js ticknow is ", ticknow);
  blink ();
}
var s = userHello();
s.hello_param(1234);
s.hello_no_param();
print ("main js OK");

register userHello func

static void
register_js_function (const char *name_p, /**< name of the function */
                      jerry_external_handler_t handler_p) /**< function callback */
{
  jerry_value_t result_val = jerryx_handler_register_global ((const jerry_char_t *) name_p, handler_p);

  if (jerry_value_has_error_flag (result_val))
  {
    rt_kprintf("Error: register global func userHello err\n");
    jerry_port_log (JERRY_LOG_LEVEL_WARNING, "Warning: failed to register '%s' method.", name_p);
  }

  jerry_release_value (result_val);
  

} /* register_js_function */

void js_register_functions(void)
{
  register_js_function ("print", jerryx_handler_print);

  // REGISTER_HANDLER (assert);
  REGISTER_HANDLER(userLed);
  register_js_function ("userHello", userHello);
}

userHello handler

extern "C" {

jerry_value_t 
userHello(const jerry_value_t func,
                     const jerry_value_t thiz,
                     const jerry_value_t *args,
                     const jerry_length_t argscount) 
{
  jerry_value_t constructed = thiz;

  // Construct object if new was not used to call this function
  {
    const jerry_value_t ownname = jerry_create_string((const jerry_char_t *)"userHello");
    if (jerry_has_property(constructed, ownname))
    {
      rt_kprintf("userHello_handler is exist!\n");
      constructed = jerry_create_object();
    }
    else
    {
      rt_kprintf("userHello_handler is not exist!\n");
    }
    jerry_release_value(ownname);
  }

  struct
  {
    const char *name;
    jerry_external_handler_t handler;
  } funcs[] = {
      {"hello_no_param", hello_no_param},
      {"hello_param", hello_have_param},
  };

  const jerry_value_t name1 = jerry_create_string((const jerry_char_t *)funcs[0].name);
  const jerry_value_t func1 = jerry_create_external_function(funcs[0].handler);
  jerry_set_property(constructed, name1, func1);

  const jerry_value_t name2 = jerry_create_string((const jerry_char_t *)funcs[1].name);
  const jerry_value_t func2 = jerry_create_external_function(funcs[1].handler);
  jerry_set_property(constructed, name2, func2);

  jerry_release_value(func1);
  jerry_release_value(name1);
  jerry_release_value(func2);
  jerry_release_value(name2);

  // Add backing object
  hello *client = new hello;
  jerry_set_object_native_pointer(constructed, client, &client_native_info);

  return constructed;
}
}

hellozimo avatar Nov 29 '17 10:11 hellozimo

Maybe take a look at @janjongboom 's mbed JS stuff. They call into C++ code from JS, for example: https://github.com/ARMmbed/mbed-js-ble/tree/master/jerryscript-mbed-ble

martijnthe avatar Nov 29 '17 12:11 martijnthe

You have two hello_param in your example. I suspect the first one is the no param.

Anyway there is no way to call functions with hidden this argument from C code, and JerryScript is C (in practice this is the first argument of c++ member functions, but I am not sure the standard specify this or just a custom).

Perhaps the easiest solution is registering the "this" as the native property of a JS object, and the handler function gets this property, converts it to object, and calls the member function. You can make a compiler define to generate these wrappers automatically.

zherczeg avatar Nov 30 '17 09:11 zherczeg

Two cases of JS script used C++ class:

  1. JS Engineer generate C++ class wrappers. Creating C++ class instance, and handling business logic in JS script. (Js single side refers to C++ member functions)
  2. JS Engineer generate C++ class wrappers. Creating C++ class instance in C++ CODE, Getting C++ class instance member functions and handling business logic in JS script. (C++ and JS code are responsible for part of the content)

Currently, my needs are the second way:
Creating C++ class(eg: class win) instance in C++ CODE(eg: win* mainWin = new win()), C++ handle a part of business logic. And in JS script, getting C++ class instance member functions and private data, then handling a part business logic in JS script. eg: I hope to handle onButton event in JS script(button.js). That means I need call C++ class(class win) member functions and it's private data in button.js.

There is a problem that I do not know how handle this case fairily. At the same time I hope the author can give a framework for handling such situation.


Code excerpt in jerryscript/target/mbedos5/jerryscript-mbed/jerryscript-mbed-drivers/source/PwmOut-js.cpp:

PwmOut* native_ptr = new PwmOut(pin_name); Create the native object, that means creating a C++ class instance in the process of JS script parsing. If I need create this instance in C++ code, how deal with it here.

DECLARE_CLASS_CONSTRUCTOR(PwmOut) {
    CHECK_ARGUMENT_COUNT(PwmOut, __constructor, args_count == 1);
    CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, __constructor, 0, number);

    PinName pin_name = PinName(jerry_get_number_value(args[0]));

    // Create the native object
    PwmOut* native_ptr = new PwmOut(pin_name);

    // create the jerryscript object
    jerry_value_t js_object = jerry_create_object();
    jerry_set_object_native_pointer(js_object, native_ptr, &native_obj_type_info);

    // attach methods
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, write);
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, read);
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, period);
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, period_ms);
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, period_us);
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, pulsewidth);
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, pulsewidth_ms);
    ATTACH_CLASS_FUNCTION(js_object, PwmOut, pulsewidth_us);

    return js_object;
}

hellozimo avatar Dec 01 '17 02:12 hellozimo

Is this problem solved?

I am not sure I fully understand the problem but I would create a JS object, attach getter functions to query C++ data, and setter functions to control the object from C++. The private pointer could be the "this" object, which needs to be C++ casted correctly.

zherczeg avatar Feb 01 '18 10:02 zherczeg

@zhaojuntao Should we keep this issue open for further discussion? Are you still facing issues with C++/JS interworking?

akosthekiss avatar May 10 '18 06:05 akosthekiss

Oops, this was not one of my repos. I think this can be closed.

janjongboom avatar May 10 '18 10:05 janjongboom

Closing as the original poster doesn't seem to follow up. Feel free to reopen the issue if there is anything left to discuss or open a new issue if there are new problems or questions.

akosthekiss avatar Jan 12 '19 11:01 akosthekiss