Converting an associative array in JavaScript to a string map in C++ with Swig: A step-by-step guide

In a situation quite reminiscent of this query, I am aiming to wrap a function using SWIG that accepts a map of strings to strings:

void foo(std::map<std::string, std::string> const& args);

Creating an alias for the map suffices for Python:

namespace std {
    %template(map_string_string) map<string, string>;
}

The code generator will automatically generate and utilize a wrapper function map_string_string.

my_module.foo({'a': 'b', 'c', 'd'})

This call will be correctly executed, with values not fitting the signature omitted.

How can I achieve this in JavaScript?

I attempted the same (naturally), and while the wrapper is generated, attempting to invoke foo like so:

my_module.foo({'a':'b', 'c':'d'});

Results in:

/path/to/example.js:3
my_module.foo({'a':'b', 'c':'d'});
          ^

Error: in method 'foo', argument 1 of type 'std::map< std::string,std::string > const &'
    at Object.<anonymous> (/path/to/example.js:8:7)
    ...

Even trying to call the wrapper function map_string_string results in this error.

Is there another way to handle "string maps" in JavaScript? Or perhaps an easy method to wrap an associative array in Swig?

Edit: In the interest of completeness, the source files used are included below:

...

In both cases - Python and JavaScript - api.foo() is working as expected. However, api.bar() runs successfully in Python but throws the mentioned error in JavaScript.

Answer №1

It appears that the latest version of swig (3.0.12) does not include built-in functionality for mapping a JavaScript object or primitive to a map. You may need to create your own converter that can take a JavaScript object and transform it into a C++ map. Check out this article for some guidance on how to do this.

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

Adjust the size of text using JavaScript to display as an image

Is there a way to adjust the size of a div with text by specifying a width and height so that it fills up the designated area, similar to how an image does when you set its dimensions? I'm looking to take any given width and height values and stretch ...

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

jQuery does not function properly when used with string variables

Why am I experiencing different results in Google Chrome when using a hard-coded string versus storing the same string in a variable? While the hard-coded string works properly, the same string stored in a variable does not produce the expected outcome. ...

Retrieval of request in iframe URL

Currently, a third party is displaying my URL within their iframe. They are limited in flexibility and simply hard code the URL I provide them with. <iframe url="https://firstURL.com"></iframe> Now, I need to distinguish between two groups of ...

Using React with SortableJS to exclude specific elements from being sorted towards the end

I have a React list that looks something like this: <div id="list"> <Item data-id="1"> <Item data-id="2"> <Item data-id="3"> <Item data-id="4"& ...

Validation in AngularJS - Setting minimum length for textarea using ng-minlength

I am currently tackling a project that heavily relies on AngularJS for the front-end. Here's what I am dealing with: The validation requirement I am aiming for is as follows: The Next button should remain disabled unless the reason provided is at le ...

Is it possible to trigger the onNewRequest property when the onBlur event is fired for AutoComplete in Material-UI?

Currently, I am utilizing Material-UI and making use of the onNewRequest property in the AutoComplete field. However, the onNewRequest only triggers when Enter is pressed or when a value is selected. I am interested in calling the onNewRequest even when ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

What is the best way to connect three or more variables with one-to-one relationships in AngularJS?

Let's say I want to create a unit converter using AngularJS. I also want the ability for multiple values to change simultaneously when editing. What I mean is, if we have 3 variables, then when one changes, the other two should automatically update. ...

Changing JSON into an array with typescript

I have encountered a JSON structure that is causing me some trouble: const help = [ { "en": [ { "test2": [ { "title": "Naslov1", &quo ...

Delivering Background Videos with Node.JS

Apologies if my question seems off base or confusing, as I am not very knowledgeable in the world of nodejs. I have been comfortable using just plain PHP and Apache for a while until I discovered ZURB Foundation's stack with Handlebars and SASS, along ...

How come I cannot declare my own type even after using Q_DECLARE_METATYPE?

Having some trouble with Q_DECLARE_METATYPE: Error Code C2280 Description: 'MyNamespace::MyClass::MyClass(const MyNamespace::MyClass&)': attempt to reference a deleted function BksMtRisk C:\qt2\5.15.2\msvc2019_64\include ...

Switch up Google Fusion URL using Jquery

Looking to modify Google Fusion query using jQuery, here is the code snippet: var fusionid= ""; function initMap() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 28.3268, lng: 84.1855}, zoom: 7 } ...

Executing a Python script in Django and transferring its output to a JavaScript file

Getting Started with Django What I'm Looking For: 1 - Execute a Python Script 2 - Pass data to a JavaScript file I'm unsure if the sentence I've constructed is technically accurate in terms of Django. Below are the JavaScript and Python ...

Using ng-repeat to iterate over an array of strings in Javascript

I am working with a JavaScript Array that contains strings: for(var i =0; i<db.length; i++) console.log(db[i]); When I run the code, the output is as follows: dbName:rf,dbStatus:true dbName:rt,dbStatus:false Now, I am trying to use ng-repeat to ...

Animated the height of a rectangle during initial loading and when the mouse hovers over or leaves

Being new to Vue.js, I am looking to create a simple animation on component load for the first time. You can find my initial code here: <template> <div id="app"> <div class="rect" /> </div> </template ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

What is the purpose of the Express 4 namespace parameter?

Having worked extensively with Express 4, I recently attempted to implement a namespaced route with a parameter. This would involve routes like: /:username/shows /:username/shows/:showname/episodes I figured this scenario was ideal for express namespacin ...

Authentication with Laravel and Vue.js

After successfully implementing Laravel-Vue.js Authentication using Passport API, I am now able to obtain the token and send requests to api/user. Initially, I used the normal authentication process by sending data through a POST request to /login, which r ...

Bringing a React Context Back to its Original State

The default state of a React Context is defined as: export const defaultState: UsersState = { isModalOpen: false, isCancelRequest: false, companyId: 0, users: [] }; After cancelling the modal, the goal is to reset the state back to its default va ...