Is it possible to utilize WebAssembly in JavaScript to access the memory of a C struct directly?

Looking at the C code snippet below, there is a struct defined as follows

typedef struct {
    ValueType type;
    union {
        bool boolean;
        double number;
        Obj* obj;
    } as;
} Value;

The ValueType enum used in the struct is defined as:

typedef enum {
    VALUE_BOOL,
    VALUE_NIL,
    VALUE_NUMBER,
    VALUE_OBJ
} ValueType;

To interact with this C code using the WebAssembly (WASM) technology, an external JavaScript file named js_library.js is created. Inside this file, there is a function called accessStruct with the signature defined in C as:

extern void accessStruct(Value value);

The implementation of the accessStruct function in JavaScript is shown below:

function accessStruct(value) {
  console.log(Module.getValue(value, "i32"));
}

However, attempting to access the remaining struct fields by incrementing the pointer does not yield the expected results. An example code snippet demonstrating this issue is given below:

function accessStruct(value) {
  console.log(Module.getValue(value, "i32"));
  const v = value + 32;
  console.log(Module.getValue(v, "i64"));
}

Given the fact that ValueType occupies 4 bytes (or 32 bits), it was assumed that accessing a double value should be possible through the line of code

Module.getValue(v, "i64")
. However, incorrect values are returned which leads to confusion and raises the question - where is the mistake?

Answer №1

The getValue function requires the first argument to be specified as the offset in bytes. The second argument should indicate the data type, which in this case should be "double" according to the documentation.

The code snippet const v = value + 32; appears to be referencing bits instead of bytes. To properly calculate the offset of a field relative to the start of the structure (in bytes), you can refer to a method like the one mentioned here. It may require implementing a C++ function to retrieve the offset and then using it in JavaScript as shown below:

function accessStruct(offset) {
  console.log(Module.getValue(offset, "i32"));
  console.log(Module.getValue(offset + offsetToValue(), "double"));
}

Furthermore, it is important to ensure that the memory addressing is set to 32 bits. Instead of specifying "i32", you could consider using "*" to cater to 64-bit memory addresses as suggested in the documentation. Additionally, utilizing a pointer to the instance might prove helpful:

extern void accessStruct(Value * value);

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

If I send a signal to a condition variable N times, will it then unblock N threads simultaneously?

Imagine I have three threads - A, B, and C. There is a mutex named 'mutex' and a conditional variable called 'cond.' Threads B and C are currently blocked on pthread_cond_wait(&cond, &mutex);. Thread A locks the mutex, then si ...

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

Retrieve the DOM variable before it undergoes changes upon clicking the redirect button

I have been struggling for a long time to figure out how to maintain variables between page refreshes and different pages within a single browser session opened using Selenium in Python. Unfortunately, I have tried storing variables in localStorage, sessio ...

Tips for invoking the href function in jwplayer with individual arguments

I need assistance with configuring jwplayer to load a list of href links one by one. Each href link includes a function that needs to be triggered automatically with specific parameters passed to JavaScript. Below is the code snippet I am currently worki ...

Is there a way for me to determine when the modal animation has completed?

I'm currently using the modal feature in twitter-bootstrap and I am curious about how long it takes for the modal to appear before triggering an alert. To better illustrate my point, you can check out this example: HTML <button id="mod" class="b ...

Locate a specific element within an array and retrieve its corresponding index

Need help updating a boolean property for all objects in an array with the same user ID. I've outlined my MVC framework below in a concise manner. Model: var posts = [{id:1, user_id:1, is_following:true}, {id:2, user_id:1, is_cool:true}, ...

Can you tell me if the "dom model" concept belongs to the realm of HTML or JavaScript?

Is the ability to use "document.X" in JavaScript to visit an HTML page and all its tags defined by the HTML protocol or the ECMAScript protocol? Or is it simply a choice made in the implementation of JavaScript, resulting in slight differences in every bro ...

React Router: Dispatch not triggering when route changes

I have multiple paths that share the same controller: <Route component={Search} path='/accommodation(/:state)(/:region)(/:area)' /> and when the route changes, I trigger the api function within the component: componentWillReceiveProps = ...

Accessing Properties in React.js: A Guide

<Element id="1" onClick={this.runFunction(???)}/> When the onClick event is triggered, I want to execute a different function with the key value "1" as an argument. How can I make this happen? Thank you. ...

Is there a script available on this page that allows me to access the Google Chrome plug-in variable?

Could you kindly clarify if a script on the webpage is able to access variables from a Chrome extension? I have developed an extension for Google Chrome and am concerned about the possibility of the website owner where the extension is running being able ...

Are You Able to Develop a Floating Window That Stays Persistent in JavaScript?

Looking to create a persistent floating window in a NextJS 14 app. This window needs to remain on top, even when navigating between browser windows. Want it to stay visible even when the browser window is minimized, like a Picture-In-Picture feature. Mos ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

Issues with Initializing Byte Arrays in C++ - Where Are We Going Wrong?

I'm currently facing an issue with a byte array in a C++ project for Arduino. The bytes are #defined in a different file that is generated elsewhere and then imported into my project. However, I'm noticing that the first two bytes in the array ke ...

How can I display a particular section of my JSON data in an AngularJS application?

Below is an example of a JSON structure: {"years":[ { "year_title":"94", "months":[...] } { "year_title":"95", "months":[...] } { "year_title":"96", "months":[...] } ]} I was able to display the data using the code sni ...

What is the best way to handle waiting for a request and user input simultaneously?

Imagine a scenario where a component loads and initiates an asynchronous request. This component also includes a submit button that, when clicked by the user, triggers a function that depends on the result of the initial request. How can I ensure that this ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

Press the designated button located within a table's td element to retrieve the values of adjacent td elements

I need to implement a functionality where clicking a button within a <td> element will retrieve the values of other <td> elements within the same row (<tr>). Here is the current implementation: $(document).ready(function(){ ...

Tips for implementing pagination in a search result by adjusting the skip and limit values within the same query

While some may argue that this question belongs on programmers.stackexchange.com, after reviewing the Help Center of Stack Overflow, I believe it is a specific programming issue and will likely receive a better response here. I have developed a webapp usi ...

The jQuery function appears to be running multiple times in a loop

For some reason, every value in my JSON object is getting added to the "listOfCountries" array twice. It seems like there might be a loop going through the result object more than once. I could really use some assistance with this issue! var listOfCountri ...

PHP script encountering difficulty inserting data into database when AJAX is utilized; functions flawlessly without AJAX

In my "user registration" file, there is a form with the following structure: <form action="" method="POST"> <label for="user" class="control-label">User </label> <input type="text" name="user" class="form-control" id="user" ...