Copyright ©

Mongoose OS Forum

ATTENTION! This forum has moved to:

Do not post any new messages.

Pass a javascript string to a C unsigned char array

I have a javascript string in init.js that I would like to access as an unsigned char array in an FFI called function. I can get FFI working with simple variables, but I can't figure out how to do this with strings or arrays (or even if it can be done). Passing a pointer to where the string lives in javascript seems to be one way to do this, but I can't figure out the syntax. Has anyone seen this type of problem? Thanks for your help, JSW


  • nliviunliviu Romania
    edited April 2018


    void string_from_js(const char* str, int len) {
      char* buf = (char*) malloc(2 * len + 1);
      for (int i = 0; i < len; ++i) {
        snprintf(buf + 2 * i, 2 * (len - i) + 1, "%02x", str[i]);
      LOG(LL_INFO, ("from js: %.*s, hex: %s", len, str, buf));


    let string_from_js = ffi('void string_from_js(char*, int)');
    let str = 'aBcDeFgH\x01\x02\x03';
    string_from_js(str, str.length);


    string_from_js       from js: aBcDeFgH   , hex: 6142634465466748010203

    C/C++ interoperability

    Thanked by 1Sergey
  • SergeySergey Dublin, Ireland
    edited April 2018
    Thanked by 1jstevewood
  • nliviunliviu Romania

    @Sergey Nice addition. The %H format specifier is not documented.

    Thanked by 1jstevewood
  • SergeySergey Dublin, Ireland

    @nliviu right! explained in the frozen.h but not in the readme. the PR is in flight to fix, thanks!

Sign In or Register to comment.