How do I interface with extern variables from Cheerp/js?

烂漫一生 提交于 2020-06-17 08:03:08

问题


Cheerp is a C++ to js/wasm transpiler. Screeps is a programming videogame.

How do I read in the Game.time variable from my transpiled C++ code? (in screeps)


#include <cheerp/client.h>
#include <iostream>
using namespace std;

namespace client {
    class Game : public Object {
    public:
        static volatile double time;
    };  

    extern volatile Game &Game;
}

void webMain() {
    cout << __TIME__ << ": The current time is: " << client::Game.time << endl;
}

I have tried any number of variations on:

  • extern, volatile and static
  • references and pointers
  • both client and cheerp namespaces
  • Inheriting from Node/Object
  • int32_t vs double vs float as a type

I seem to get either:

  • NaN
  • 0
  • 1
  • fatal type handling errors in the compiled code

How do I correctly interface with Javascript Objects and variables from within my C++ code? The cheerp documentation is VERY sparse to say the least...


Note: cheerp is never actually generating the proper Javascript. There's always some inconsistency as to how the Game object is handled and in a lot of scenarios it's incorrectly trying to index Game.d as an array instead of Game.time.


回答1:


Classes declared in the client namespace should have no member fields.

To access external JS objects properties you need to add methods starting with get_ and set_, to respectively read and write to the property:

#include <cheerp/client.h>
#include <iostream>
using namespace std;

namespace client {
    class Game : public Object {
    public:
        double get_time();
    };  

    extern Game &Game;
}

void webMain() {
    cout << __TIME__ << ": The current time is: " << client::Game.get_time() << endl;
}


Also, you don't need to use volatile here.



来源:https://stackoverflow.com/questions/62378053/how-do-i-interface-with-extern-variables-from-cheerp-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!