Call C++ Emscripten binded function with SDL2 in it from JS

148 views Asked by At

I am struggling with running compiled c++ code. I want to call it from JS. The c++ code is below:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <SDL2/SDL.h>
#include <assert.h>
#include <emscripten.h>

SDL_Window * window;
SDL_Renderer * renderer;

std::vector<int> datas;

void render_func(void) {
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(renderer);

    
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
    int x = 300;
    int y = 200;
    for(int i = 0; i < datas.size() - 1; i ++)
    {
        SDL_RenderDrawLine(renderer, x + 10 * i, y - datas[i] * 3, x + 10 * (i + 1), y - datas[i + 1] * 3);
    }
    SDL_RenderPresent(renderer);

    emscripten_cancel_main_loop(); //cancel ems loop
}

void draw()
{
    datas = {1,15,7,3,20};
    
    //Draw data
    assert(SDL_Init(SDL_INIT_VIDEO) == 0);
    SDL_CreateWindowAndRenderer(640, 320, 0, &window, &renderer);

    emscripten_set_main_loop(render_func, 60, 1); //start ems loop

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

#ifdef EMSCRIPTEN
    #include <emscripten/bind.h>
    using namespace emscripten;

    EMSCRIPTEN_BINDINGS(module) {
        emscripten::function("draw", &draw, allow_raw_pointers());
    }
#endif

And the .html page with JS code is like this:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Main window</title>
  </head>

  <script>
    var Module = {
      onRuntimeInitialized: async function() {
        Module.draw();
      }
    }
  </script>
  <script src="./example.js"></script>

</html>

I compile like this:

emcc -lembind -o example.js example.cpp -s USE_SDL=2

When I run open the .html page with JS code in it it throws an error:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'addEventListener')
    at Object.registerOrRemoveHandler (example.js:1:120672)
    at registerMouseEventCallback (example.js:1:173607)
    at _emscripten_set_mousemove_callback_on_thread (example.js:1:174395)
    at 002b5136:0x4b7f8
    at 002b5136:0x7bd71
    at 002b5136:0x6f0ea
    at Object.draw (eval at new_ (example.js:1:76673), <anonymous>:7:1)
    at Object.onRuntimeInitialized (test.html:11:16)
    at doRun (example.js:1:205344)
    at run (example.js:1:205504)

But compiling c++ code straight to .html file work perfectly and .html file opens and there is a small drawing shown. But no luck with compiling c++ to .js and calling .js from .html. Am I missing something?

0

There are 0 answers