Copyright © https://mongoose-os.com

Mongoose OS Forum

frame

Passing JavaScript object to/from C/C++

Can a (pointer to a) JavaScript object be passed to a C/C++ function and its contents read/changed? Is there an example where this is done?

Comments

  • I did something like that to pass a C structure from the bme280 library to mJS using create/delete/get functions in C.
    Eg:

    let bmeAddress = 0x76;
    let bme = BME280.createI2C(bmeAddress);
    let data = BME280Data.create();
    
    let readAll = function () {
        let start = Timer.now();
        let res = bme.readAll(data);
        let delta = (Timer.now() - start) * 1000000;
        if (0 === res) {
            return JSON.stringify({
                temperature: data.temp(),
                pressure: data.press() / 100.0,
                humidity: data.humid(),
                type: 'readAll',
                delta: delta
            });
        } else {
            return '=== Error reading BME';
        }
    };
    
  • Thanks for the suggestion; it's definitely a valid solution.

    I was hoping there was a way of passing structures between C++ and JavaScript without going via JSON strings - I had wanted to avoid this, and thought MJS may have defined a way of accessing struct members of standard types (int, void*, etc) via names if one kept within certain rules. The other option I can think of is to use wrapper functions on both sides, including a callback from C++ to JavaScript, which might be a better solution than JSON strings in my particular case.

    Anyway, if anyone comes across this post and has a better/alternative idea than those two options, I'd love to hear it.

Sign In or Register to comment.