Convert C language to JavaScript with Emscripten

I think C is the strongest cross-platform language, iOS can also use C language in Objective-C, Android can also use C language with NDK, so I thought that if all the logic other than the UI was written in C, it could be used on all platforms. However, with FireFoxOS, I couldn't do that, and I couldn't use C language in the form of calling the API of basic JavaScript.

I was at the bottom of my disappointment, Emscripten was one of the breakthroughs! !! !! !!

What is Emscripten?

Emscripten is a compiler that generates LLVM from the C / C ++ language and converts it to JavaScript. It also supports the C language standard library and part of POSIX, and it seems that OpenGL ES 2.0 can also be used. Emscripten itself is below. https://github.com/kripken/emscripten

Ready (Mac OS X)

Enables emscripten.

I tried various things, but installing the SDK was the easiest.

As a procedure, http://kripken.github.io/emscripten-site/docs/building_from_source/building_emscripten_from_source_using_the_sdk.html#building-emscripten-from-source-using-the-sdk You can do as written in.

If you write the procedure https://s3.amazonaws.com/mozilla-games/emscripten/releases/emsdk-portable.tar.gz Get the source code from.

Because I use CMake

python


$ brew install cmake

Please do. After unzipping the code

python


$  cd emsdk_portable
$ ./emsdk install sdk-incoming-64bit
$ ./emsdk activate sdk-incoming-64bit

You can do it. It seems to use node and python for execution, so

python


$ brew install node

And After that, create a symbolic link to python2

python


$ sudo ln -s /usr/bin/python2.7 /usr/bin/python2

Run

python


$ emsdk_portable/emscripten/incoming/emcc first.c -o first.js

Then you can convert it to JS. (Maybe you should put it in PATH in emsdk_portable / emscripten / incoming /)

For example

first.c


#include <stdio.h>

int
main(void)
{
  printf("Hello, World!\n");
  return 0;
}

If

python


$ emcc first.c -o first.js
$ node first.js
Hello, World!

It will be.

Call a C function from JavaScript

For example

second.c


int
add(int x, int y) 
{
  return x + y;
}

Suppose you want to call the function from outside JavaScript. At that time, at the time of js conversion,

python


$ emcc second.c -s EXPORTED_FUCTIONS="['_add']" -o second.js

Specify the function to be published in EXPORTED_FUCTIONS and raise it. Add "_" to the function name first. After that, it is possible to call it with ccall from the js side. It is used in the form of ccal (function name, return type, [argument type], [actual argument]).

second.html


<html>
<body>
<div id="output"></div>
<script type="text/javascript" src="./second.js"></script>
<script type="text/javascript">
  var num = ccall("add", "number", ["number", "number"], [1, 2]);
  document.getElementById("output").innerHTML = num;
</script>
</body>
</html>

This will output 3 to the div. You can also use Module.cwrap to retrieve the function. Module.cwrap (function name, return type, [argument type]) You can retrieve the function in the form of.

second2.html


 <html>
<body>
<div id="output"></div>
<script type="text/javascript" src="./second.js"></script>
<script type="text/javascript">
  //Extract a function called add
  var add = Module.cwrap("add", "number", ["number", "number"]);
  //Use the extracted function
  var num = add(1, 2);
  document.getElementById("output").innerHTML = num;
</script>
</body>
</html>

Again, 3 is output to the div.

Call JavaScript from C

Conversely, when calling JS from C code,

python


mergeInto(LibraryManager.library, {
  //Definition of method called from C
});

Is used.

For example

thirdlib.js


mergeInto(LibraryManager.library, {
    jsPower: function(x) {
        return x * x;
    }
});

With a JavaScript file called

third.c


#include <stdio.h>
#include <math.h>

int jsPower(int x); //JavaScript function

int 
pythagorean(x, y)
{
  //Calculate by calling the JavaScript function jsPower
  return  sqrt(jsPower(x) + jsPower(y));
}

int
main(void)
{
  printf("%d\n", pythagorean(3,4));
  return 0;
}

Prepare a C language file called. Therefore, specify the JS code with the --js-library option, compile and execute it.

python


$ emcc third.c --js-library thirdlib.js -o third.js
$ node thired.js
5

The JS code is properly called and calculated.

Call a C ++ function from JavaScript

From here on, EMSCRIPTEN_BINDINGS can be used in C ++, and if you register it here, you can call the function in Module.xxx.

firstcpp.cpp


#include "emscripten/bind.h"

using namespace emscripten;
int
add(int x, int y)
{
  return x + y;
}

EMSCRIPTEN_BINDINGS(my_module) {
  function("add", &add);
}

Compile as follows (em ++ because it is C ++)

python


$ em++ firstcpp.cpp -o firstcpp.js -std=c++0x --bind

Using the file output as

firstcpp.html


<html>
<body>
<div id="output"></div>
<script type="text/javascript" src="./firstcpp.js"></script>
<script type="text/javascript">
  var num = Module.add(1, 2);
  document.getElementById("output").innerHTML = num;
</script>
</body>
</html>

If so, 3 will be output.

Other

I will do the above as well.

Recommended Posts

Convert C language to JavaScript with Emscripten
Convert Markdown to HTML with flexmark-java
Convert Swift 2D array to C 2D array
How to switch thumbnail images with JavaScript
How to run Blazor (C #) with Docker
Convert JSON to TSV and TSV to JSON with Ruby
Convert from C String pointer to Swift String type
Convert a string to a character-by-character array with swift
I tried to move Hello World (+ α) written in C language from JavaScript [WebAssembly]
NLP4J [006-034c] 100 language processing knocks with NLP4J # 34 Try to solve "A's B" smarter (final edition)
How to embed JavaScript variables in HTML with Thymeleaf
Generate JavaScript with Thymeleaf
Port C code with a lot of typecasts to Swift
Back to top button made only with Javascript (rails, haml)
Let's rewrite the C language assignment of the university with Node.js
Convert 2D array to csv format with Java 8 Stream API