Why are ccall and cwarp functions important in Emscripten?

I have been following the guidelines provided in the Emscripten documentation here, and I am interested in experimenting with basic examples. My ultimate objective is to develop a C++ library, compile it into a single wasm binary file, and then utilize these compiled functions in a frontend web application.

I am puzzled about the need for calling C++ methods with "ccall" when it seems like they can be accessed directly from "Module". For instance, instead of using

Module.ccall('doubleNumber','number', ['number'], [9]);
, I could just use Module._doubleNumber(9);, which appears to be simpler.

Can someone explain the distinction between these two approaches?

Below is the complete code snippet:

extern "C" {
    int doubleNumber( int x ) {
        int res = 2*x;
        return res;
    }
}

Compiled command:

emcc main.cpp -o main.js -sEXPORTED_FUNCTIONS=_doubleNumber -sEXPORTED_RUNTIME_METHODS=ccall

I am utilizing a straightforward HTML document to evaluate the outcomes:

<html>
<head>
    <meta charset="utf-8">
    <title>WASM Demo</title>
</head>
<body>
    <script type="text/javascript" src="main.js"></script>   
    <script type="text/javascript">
        Module.ccall('doubleNumber','number', ['number'], [9]); // 18
        Module._doubleNumber(9); // 18
    </script> 
</body>
</html>

Answer №1

Although in this small example there may not be a noticeable difference, it is important to consider potential issues that may arise in larger projects.

  1. In smaller tasks, the asynchronous call can be achieved using Module.ccall with the parameter async=true, while calling the exported function Module._doubleNumber will always be synchronous and block execution.
  2. When using higher optimization levels (-O2 and above), the closure compiler may minify (change) function names, making a minified name for _doubleNumber unpredictable and causing Module._doubleNumber to be undefined.
  3. To prevent name minifying and ensure proper function referencing, use
    -sEXPORTED_FUNCTIONS=_doubleNumber
    for small C libraries. However, for larger C libraries, it may be necessary to list numerous items in EXPORTED_FUNCTIONS, taking into consideration the limitations of command line length.

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

Consideration of tiebreakers in the longest word array

function findLongestOfThreeWords(word1, word2, word3) { word1 = word1.split(' '); word2 = word2.split(' '); word3 = word3.split(' '); var newArr = word1.concat(word2,word3); var longestWord = []; var longestWor ...

Naming variables in JavaScript with parentheses()

I'm currently facing some issues with my code, as it's not working properly. I have three variables that set the state of another set of three variables. Instead of writing out the code three times, I wanted to use another variable (like 'i& ...

Looking for a JavaScript function that can utilize AJAX to execute PHP code and display the PHP output on the webpage

I've been trying to use JavaScript to execute some PHP code and then display the results on the page. I came across a piece of code that achieves this using ajax and by placing the PHP code in an external file. However, the code I found seems to show ...

Submit form using jQuery after making an AJAX request with jQuery's $

I'm working on the following code: $.get(link, function(data, status) { document.getElementById("test").value = data; }); $('#formtest').submit(); Everything works fine in Firefox, but in Google Chrome the submit is done before t ...

I receive an [object HTMLCollection] as the output

I am currently working on recreating a login page and I want it so that when the button is clicked, it displays the name you entered, but instead, it returns [object HTMLCollection]. My expectation was to have the name displayed as entered. var nombre ...

"Why does Sequelize migration successfully create a table, yet the models are unable to establish a connection to the

I am currently learning how to use the Sequelize ORM in Node.js and save data in a PostgreSQL database. My primary objective is to insert user data into the Users table. I have successfully created the table using migration; however, I am encountering dif ...

How can I connect the box using the Interactive Picture jQuery tool?

When using the Interactive picture jQuery, I have the following code snippet within my document: jQuery(document).ready(function(){ $( "#iPicture6" ).iPicture({ animation: true, animationBg: "bgblack", animationType: "ltr-slide ...

Include jQuery, jQuery UI, and plugins seamlessly to avoid any version conflicts

My goal is to inject my custom code into a webpage using a bookmarklet. This code requires jQuery, jQuery UI, and additional plugins to be included on the page. I'm aware of the noConflict function, but I have concerns about potential conflicts if ot ...

React hook not working to update state across multiple components

My code consists of a hook and 2 components: App.js and New.js. The issue I'm facing is that when the state in the hook is changed by a function in App.js, the value is not updated in New.js. I have reviewed my code multiple times but still can't ...

Best practices for uploading an array of objects (multiple image files) using Node.js

Encountering an issue in my application where I need to upload multiple photos. The object consists of motherPhoto, fatherPhoto, spousePhoto, and siblingsPhoto: { "mothername": "kerin", "motherPhoto": "C:/fakepath/mot ...

Retrieving information from subscription

I am currently diving into Angular 2 and have successfully fetched data from my service. However, before displaying it on the view, I need to iterate over it using a for() loop. To achieve this, I have stored the fetched JSON data into an array. But I&apos ...

Methods for transferring data to controller in Angular Modal service

After implementing the angular modal service discussed in this article: app.service('modalService', ['$modal', function ($modal) { var modalDefaults = { backdrop: true, keyboard: true, m ...

Guide to navigating to a particular element using PerfectScrollbar

Currently, I am facing a minor challenge while creating my website using the incredible Black Dashboard template for Bootstrap 4. This template, which can be found at (many thanks to Tim for this!), utilizes PerfectScrollbar for jQuery. Although I have ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

Incorporate a new attribute into a JSON string using Jackson JSON library

Currently, I am saving a JSON string into a text field within a MySQL database. Following the insertion process, my goal is to enhance the JSON string by incorporating the MySQL line ID using Jackson JSON. Within my Java application, I have a String that ...

"Proceeding without waiting for resolution from a Promise's `.then`

I am currently integrating Google Identity Services for login on my website. I am facing an issue where the .then function is being executed before the Promise returned by the async function is resolved. I have temporarily used setTimeout to manage this, b ...

What is the best way to eliminate mouse click release events?

Encountering an issue with my Vue/Vuetify Dialog that closes when clicking outside of it as expected. The problem arises when there is a text field inside the dialog. If I accidentally select the content and release the mouse outside of the dialog, it als ...

Simulating npm package with varied outputs

In my testing process, I am attempting to simulate the behavior of an npm package. Specifically, I want to create a scenario where the package returns a Promise that resolves to true in one test and rejects with an error in another. To achieve this, I hav ...

React: Managing various browsers and browser tabs to prevent duplicate operations

On my webpage, I have a button labeled Submit that, when clicked, triggers an operation by calling an API. After the button is clicked, it should be disabled or changed to reflect that the operation has started. I am facing an issue where multiple browser ...

When no values are passed to props in Vue.js, set them to empty

So I have a discount interface set up like this: export interface Discount { id: number name: string type: string } In my Vue.js app, I am using it on my prop in the following way: export default class DiscountsEdit extends Vue { @Prop({ d ...