Using JavaScript to invoke a C++ function

In my C++ method, its purpose is to terminate certain processes and requires two parameters: a hostname and a port.

Meanwhile, I am in the process of developing a web-application using Node.js and AngularJS which runs on Google Chrome browser. When I click on a button in the browser, I want to be able to invoke the C++ function from my app.js file.

I have been unable to figure out how to connect JavaScript with C++.

UPDATE: I came across this helpful link discussing how to utilize a C++ library from node.js: How can I use a C++ library from node.js?

Answer №1

To utilize the power of Google's V8, you can integrate it with your application. This open source JavaScript engine, developed by Google, is versatile and efficient.

For more information on V8, visit: http://code.google.com/p/v8/

Explore a practical demonstration of binding a C++ class with Google V8 on GitHub: v8_wrap_class.cpp - Courtesy of Nicholas

/*
 * v8_wrap_class.cpp
 *
 *  Created on: 14/01/2013
 *      Author: nicholas
 *     License: public domain
 */

// C++ code snippets demonstrating integration of JavaScript with V8

...

Answer №2

In this response, four strategies for incorporating C++ into JavaScript are explored. The approaches presented aim to maintain the integrity of the original C++ code through standard and simple implementation techniques.

The discussion covers two methodologies utilizing WebAssembly (WASM) and two involving SWIG and JRPC. Detailed examples are provided for running C++ in both web browsers and Node.js environments using WASM. Additionally, alternative methods for executing C++ in JavaScript - such as invoking Node.js from a browser using jrpc-oo - are outlined towards the end.

To integrate your C++ code with JavaScript, consider compiling it to WASM and loading the module in either the browser or Node.js for execution. A helpful resource on leveraging WASM for this purpose can be found in this WASM repository. Key snippets from the repository are elaborated upon within the text.

Begin by defining your C++ code and declaring the corresponding WASM bindings, as shown in the example below:

// Example implementation
class Test {
  public:
    void sayHello(){
      printf("Hi, my name is test\n");
    }
};

#include <emscripten/bind.h>
EMSCRIPTEN_BINDINGS(Test_ex) {
  emscripten::class_<Test>("Test")
  .function("sayHello", &Test::sayHello)
  ;
}

After compiling the code, execute it in Node.js using a snippet like the one below:

libWASM = require('./libwasmNode.js');
libWASM().then((mod)=>{
  libWASM = mod;
  let test = new libWASM.Test;
  test.sayHello();
});

For browser implementation, import the necessary WASM library and trigger the execution of the C++ method as indicated below:

// Importing required modules
import modProm from './libwasm.js';

// Creating a web component and executing WASM code
export class LibWASM extends LitElement {
  constructor() {
    super();
  }

  async connectedCallback() {
    await modProm().then((mod)=>{
      this.libWASM = mod;
      this.WASMReady();
    })
  }
    
  WASMReady(){
    console.log('LibWASM.libWASM module compiled and ready to go.')
    let test = new this.libWASM.Test;
    test.sayHello();
  }
}

The exemplary code discussed above is available in the provided repository. Alternatively, another approach involves combining C++, SWIG, and Node.js, details of which can be found in this accompanying repository link.

For executing Node.js functionality from a browser or exploring different integration methods of C++ with Node.js, refer to this SWIG and jrpc-oo reference. These approaches facilitate seamless interactions between C++ and JavaScript while preserving the original C++ code within the project.

While there exist multiple ways to incorporate C++ into JavaScript, the highlighted strategies prioritize simplicity and reliability, focusing on WASM binding and SWIG abstraction for an effective integration process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changes made to the Redux store are not being reflected throughout the application

I have a React application that uses React and react-redux. I have successfully set up my own API. The issue I am facing is with storing the user object in the store after logging in. Although I can retrieve the user object after login, I encounter difficu ...

Ways to eliminate the lower boundary of Input text

Currently, I am working on a project using Angular2 with Materialize. I have customized the style for the text input, but I am facing an issue where I can't remove the bottom line when the user selects the input field. You can view the red line in t ...

How come defining the state using setTimeout does not display the accurate properties of a child component?

Presented here is a component designed to render a list of items and include an input for filtering. If no items are present or if the items are still loading, a message should be displayed. import { useState } from "react"; export const List = ...

What is the module system that fabric composer utilizes for its logic JavaScript files?

I am currently in the process of creating a business-network-definition for Hyperledger using Fabric (based on generator-hyperledger-fabric). Everything has been running smoothly so far, but as we move onto our Proof of Concept (PoC), a few questions have ...

Canvas with a button placed on top

I am working with a canvas and trying to position an HTML element over it using CSS. My goal is for the button to remain in place on the canvas even when resizing the entire page. Here is the code I am currently using. https://jsfiddle.net/z4fhrhLc/ #but ...

Is there a way to use jQuery to permanently add elements and have them incrementally numbered, such as Cam 1, Cam 2, Cam 3, and so on, while using an iframe?

https://i.sstatic.net/XaYGc.pngRecently, I implemented a video streaming feature on my website. The default camera displayed is Cam 1 as shown in the code snippet below: <div class="card mb-3"> <div class="card-header"> <i class ...

Instructions for launching an Android app from a website

Is it possible to invoke my app from HTML? For instance, I am able to successfully call a webpage from my app using this code. android code: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse( "myDomain.com"))); ...

Discovering the Secret TD Value Upon Clicking a TR Element

I am currently in the process of creating a web-based task manager to monitor tasks at work using HTML and PHP. I want to display all the tasks in a table, and when clicking on a task (row), I aim to retrieve a hidden td value (task ID) and pass it as an a ...

Perform an Ajax call just one time

$('#addToCart').click(function () { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let trTable = $(this).parents('div')[1]; let customPrice = $($(trTable).children('div') ...

Is there a way for me to confirm if a node module is compatible with bundling in Webpack and running in a web browser?

One of the advantages of using Webpack is its ability to bundle up node modules for use in an HTML page within a browser. However, not all node modules are compatible for this purpose. Certain modules, such as those utilizing the 'fs' module or n ...

Engage in a conversation with a specific individual on the internet using node.js

Looking to implement a chat feature with specific online users similar to Facebook or Gmail using node.js and socket.io. Can anyone assist me with this? Thanks in advance! Client.html <html> <head> <title>My Chat App</title> <d ...

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

Tips for verifying phone numbers on an HTML form

Need assistance with validating a 10-digit number input. The first two digits must be either '05' or '06'. Seeking guidance on how to achieve this validation in PHP or JavaScript. Appreciate any help, thanks! ...

Avoiding URL images on 404 errors in frontend applications

My goal is to dynamically implement images (from image_url_1.jpg to image_url_5.jpg) based on a specific URL. While everything works fine, I encounter an issue when a particular image, like "image_url_4.jpg," is not available and results in a 404 Error cau ...

The RangeError occurs when attempting to deploy to Heroku due to exceeding the maximum call stack size at Array.map in an anonymous function

While attempting to deploy a MERN stack application to Heroku, I encountered an error in the Heroku CLI. RangeError: /tmp/build_c861a30c/frontend/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js: Maximum call stack size exceeded at Array. ...

Modify a Google Docs script for use in Google Sheets

I created a function called "myFunk()" that works flawlessly in Google Docs. It essentially looks for fields marked with ## in a sheet and replaces them with user input. However, when I attempt to run it in Sheets after making some changes to the functions ...

Timing with Three.js - the key to engaging interactive experiences

Lately, I've been discovering some amazing interactive shorts created with three.js. Take a look at this example: I'm curious about the timing mechanism used in these creations. Are there any known libraries for that? The synchronization of mu ...

Transferring a method through two layers of hierarchy

I'm currently working on a fun little game project, but I've hit a roadblock when it comes to passing a particular method down to its grandchildren components. Despite finding similar discussions on this topic, none seem to address my specific qu ...

Strange behavior exhibited by ngMessage in AngularJS when used with input of type "email"

I recently came across an article on transitioning from using ngModel.$parsers and ng-if to ngModel.$validators and ngMessages by Todd Motto on his blog. Intrigued, I decided to migrate from using ng-if to ng-messages in my code. However, I encountered a s ...

What is the best way to modify or revise meta fields for individual products in order to retrieve multiple images for each product in Shopify?

What is the process for updating or editing meta fields to display multiple images of each product on Shopify? ...