Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to call a JavaScript function from C++?
Calling a JavaScript function directly from C++ depends on the environment and the system; for this, make sure you have embedded a JavaScript engine or integrated C++ with JavaScript.
In this article, we will be using Emscripten (C++ to JavaScript in WebAssembly) to call a JavaScript function from C++. For this, you have to compile the C++ program to WebAssembly using Emscripten and then call JavaScript functions from C++. So, first, create the C++ file with the header <emscripten.h>.
How Emscripten Works
Emscripten compiles C++ code to WebAssembly, which runs in browsers. The compiled WebAssembly module can interact with JavaScript through defined interfaces, allowing bidirectional function calls between C++ and JavaScript.
C++ File
Let's consider that this file name is saved as main.cpp.
#include <emscripten.h>
// here declared an external JS function
extern "C" {
extern void jsFunction();
}
int main() {
// calling the JS function from C++
jsFunction();
return 0;
}
JavaScript Function File
This is a JS function that is called from a C++ file. Consider it to be saved as the name lib.js.
mergeInto(LibraryManager.library, {
jsFunction: function() {
console.log('Hello from JavaScript!');
}
});
Compilation Process
Now, to compile this, open the command prompt and go to your project folder.
cd path\to\your\project
Then run this command:
emcc main.cpp -s EXPORTED_FUNCTIONS="['_main']" -s EXTRA_EXPORTED_RUNTIME_METHODS="['ccall', 'cwrap']" --js-library lib.js -o output.html
Output
After compilation, open the generated output.html file in a browser. The output will be displayed in the browser's developer console:
Hello from JavaScript!
Alternative Approaches
| Method | Environment | Complexity | Use Case |
|---|---|---|---|
| Emscripten | Browser | Medium | Web applications |
| Node.js N-API | Node.js | High | Server-side extensions |
| V8 Engine | Desktop | High | Embedded JavaScript |
| QuickJS | Desktop | Medium | Lightweight integration |
Key Points
- Emscripten requires the extern "C" declaration to prevent C++ name mangling
- JavaScript functions must be defined in a library file using mergeInto
- The compiled output includes HTML, JavaScript, and WebAssembly files
- Function calls are synchronous within the WebAssembly environment
Conclusion
Emscripten provides an effective way to call JavaScript functions from C++ in web environments. For server-side applications, consider Node.js Native Addons or embedded JavaScript engines like V8.
