Transfer of double array in Emscripten - A seemingly arbitrary address has been obtained

I am facing a challenge in passing a double array to a WASM file that is generated through emscripten. I have created it as a .js output file with WASM=1, which also gives me a wasm file.

Below is an excerpt from my C++ code:

#include <iostream>
using namespace std;

extern "C" {

  int main(int argc, char** argv) {
    return 0;
  }

  double *calculate(double *x, double *y, int array_length) {
    std:cout << "Array Length: " << array_length << endl;
    for (int i = 0; i < array_length; i++) {
      std::cout << "Coords: " << x[i] << ", " << y[i] << endl;
    }
    return new double[7]{1,1,2,3,5,8,13};
  }
}

The browser console output shows:

Array Length: 4 average.js:8:16057
Coords: 2.36377e+232, 2.36377e+232 average.js:8:16057
Coords: 5.9419e-310, 5.9419e-310 average.js:8:16057
Coords: 4.28375e-319, 4.28375e-319 average.js:8:16057
Coords: 1.4854e-313, 1.4854e-313

Although the code seems to work, I am unsure why the browser output is generated as such. Even when changing the input values in the array, the printed values remain unchanged (except for the quantity). It appears that the c++ code might not be receiving the array properly and instead reading from default allocated memory space. But why?

Answer №1

I attempted this process only once, and while I am not an expert, I was able to successfully pass an array of doubles from JavaScript to C++ using the following method.

My understanding is that in order to access memory from JavaScript, one must acknowledge the differing memory layouts between JavaScript and WebAssembly. Utilizing HEAPF64.set allows for data to be copied from a JavaScript array (with its unique memory layout) to the Emscripten HEAP, enabling access by the WebAssembly module.

Below is my example, which is in node.js format (my apologies for the restriction), but a similar approach should be applicable in a browser setting as well.

const factory = require('./src/passarray.js');
factory().then(instance => {
  const doubleArray = new Float64Array([1.0, 2.0, 3.0, 4.0, 5.0]);

  const arrayPointer = instance._malloc(doubleArray.length * doubleArray.BYTES_PER_ELEMENT);
  instance.HEAPF64.set(doubleArray, arrayPointer / doubleArray.BYTES_PER_ELEMENT);

  instance._exampleFunction(arrayPointer);

  instance._free(arrayPointer);
});

For the C++ implementation:

extern "C" {
  EMSCRIPTEN_KEEPALIVE
  void exampleFunction(double* elems) { 
    // [your code here]
  }
}

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

C++ Catastrophe (Compiler Conundrum?)

I'm encountering a frustrating issue with my basic program. Every time I try to run it, it crashes when it reaches "has an initial population of." Just for reference, I am using visual studio 2015 on windows 10. #include <iostream> #include < ...

Utilizing PrimeNG menu items to bind commands to a base class function

I'm struggling to connect a parent class function with my Angular 2 PrimeNG menu options. HTML <p-menu #menu popup="popup" [model]="exportItems"></p-menu> <button type="button" class="fa fa-download" title="Export As" (click)="menu.to ...

Is it risky when 2 threads from separate warps within the same block in CUDA try to write to the same shared memory location?

Is there potential for inconsistencies in shared memory with this approach? Here is a snippet of my kernel code (in pseudocode): __shared__ uint histogram[32][64]; uint threadLane = threadIdx.x % 32; for (data){ histogram[threadLane][data]++; } Co ...

Competing in a fast-paced race with JavaScript promises to guarantee the completion of all

How can I retrieve the result of a Javascript Promise that resolves the fastest, while still allowing the other promises to continue running even after one has been resolved? See example below. // The 3 promises in question const fetchFromGoogle: Promise&l ...

Error encountered when utilizing -D_FILE_OFFSET_BITS=64 on Solaris leads to lseek issues

While compiling my application on Unix, I am using the -D_FILE_OFFSET_BITS=64 flag. The build is successful on RHEL, SuSE, HP-uX, and AIX. However, on Solaris, I encounter an error with the following code snippet: long lPos = 0L; long UTMPSIZE = sizeof(s ...

Developing with Ionic 2 allows you to efficiently run a background service using Cordova

I am currently using Ionic 2 and I have a requirement for my app to perform certain tasks even when it is closed, similar to how Gmail continues to provide notifications all the time. After some research, I came across this documentation: https://ionicfr ...

Problem encountered when trying to deploy a Next.js application with React Hook Form v7 on Vercel platform

I am currently in the process of creating a web application using nextjs and chakra UI while incorporating typescript. I've integrated react hook form for form validation, however I encountered a problem when deploying it on vercel. Check out the scre ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

When trying to access the value in the constructor function, an error occurs in the render function that says "TypeError: Cannot read property 'xxx' of undefined."

When the code console.log(data["users"]["userId"]["points"]) is executed within the getData() function, the output is 20. However, in the render() function: <Text>{JSON.stringify(this.state.users.userId.points)}</Text>, an error is thrown ...

Using a substitution cipher for encryption will result in output that is not valid ASCII

I'm struggling to understand why the error message "output not valid ASCII text" keeps appearing! To provide some context on the issue at hand, I will outline what needs to be done. THIS IS WHERE IT BEGINS! In a substitution cipher, we encode a mess ...

Identify and correct the invalid item within an array form

https://i.sstatic.net/33oNr.png How can I target and focus on an invalid item in a form array? I have attempted the following using nativeElement focus, but I am not able to pinpoint the exact invalid control. if (this.basicForm.invalid) { const ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

Exploring the Power of JSONObject and JSONArray in Jmeter

Having an issue with constructing a Json for Amazon Kinesis. The Json needs to follow this format: { "Records": [ { "Data": "XzxkYXRhPl8x", "PartitionKey": "partitionKey1" }, { "Data": "f1PxF ...

Merging two arrays using just one dictionary

I am currently fetching two JSON arrays and storing them in variables named json_one and json_two. Everything is working properly, but now I want to merge them into a single array. What is the best way to combine 2 Arrays with one dictionary? json_one [ ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

The function called within the XState machine cannot be invoked from within the class, yet it functions properly when defined as a

Is there a reason why I can't reference a method declared within the same class as XState service? It seems to work fine when the method is moved outside of the class. export class LoaderMachine { service = interpret(createMachine<LoaderContext ...

Exporting modules/namespaces to the window object in TypeScript

I have experience building APIs and applications in ES2015, but I am still learning the best practices for TypeScript. Can someone assist me with this challenge? Suppose I am creating an API/SDK for a shop. The objective is for the user to include my js f ...

Transforming a two-column text document into a set of key-value pairs

Recently, I've been diving into the world of Node.js and Express. My current challenge involves converting a text file into key-value pairs. The approach I'm taking with my staircase program is as follows: https://i.sstatic.net/GPs200IQ.png Th ...

The name 'XXX' is nowhere to be found

I encountered an error stating "Cannot find name 'Calendar Component'" while attempting to add a route to a component from another module in my app.module.ts file. Below is the content of my app.module.ts file: // Importing Modules // import {B ...

Getting a WebRTC call from a C++ application designed for Windows platform

Looking to receive video/audio data from a browser at a remote location using C++ in a native Windows application. It appears that WebRTC is the most suitable option for this task. While most resources focus on creating WebRTC apps within the browser, I a ...