【问题标题】:How to map an associative array in JavaScript to a string map in C++ using Swig?如何使用 Swig 将 JavaScript 中的关联数组映射到 C++ 中的字符串映射?
【发布时间】:2018-12-07 06:36:18
【问题描述】:

非常类似于this question 我想用 SWIG 包装一个函数,它将 mapstrings 转换为 strings:

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

对于 Python,为地图创建别名就足够了:

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

代码生成器会创建一个包装函数map_string_string,甚至会自动使用它。

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

将被正确调用,不符合签名的值将被忽略。

如何为 JavaScript 执行此操作?

我尝试了同样的方法(当然)并且生成了包装器,但是当我尝试像这样调用 foo 时:

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

我明白了

/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)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

即使我尝试调用包装函数 map_string_string 我也会收到此错误..

还有另一种在 JavaScript 中编写“字符串映射”的方法吗?还是有一个简单的收据可以在 Swig 中包装一个关联数组?

编辑:为了完整起见,我添加了我使用过的源文件:

api.h

#pragma once

#include <string>
#include <map>
#include <iostream>

static void foo(std::string const& value) noexcept {
  std::cout << value << std::endl;
}

static void bar(std::map<std::string, std::string> const& args) noexcept {
    for (auto && e : args) {
        std::cout << e.first << ": " << e.second << std::endl;
    }
}

api.i

%module api 
%include "std_string.i"
%include "std_map.i"
namespace std {
    %template(map_string_string) map<string, string>;
}
%{
    #include <api.h>
%}
%include "api.h"

这是我构建 Python 和 JavaScript 模块的方式:

swig -c++ -python -o api_wrap_python.cxx api.i 
g++ -c api_wrap_python.cxx \
    -I/usr/include/python3.6m -I . \
    -fPIC -std=gnu++11
g++ -shared api_wrap_python.o -o _api.so

swig -c++ -javascript -node -o api_wrap_js.cxx api.i
g++ -c api_wrap_js.cxx \
    -I /usr/include/node -I . \
    -std=gnu++11 -fPIC -DBUILDING_NODE_EXTENSION
g++ -shared api_wrap_js.o -o api.node

最后这就是我测试它们的方式:

node -e "api = require('api.node'); api.foo('some string'); api.bar({'a':'b'});"
python3 -c "import api; api.foo('hello'); api.bar({'a':'b','c':'d'})"

在这两种情况下 - Python 和 JavaScript - api.foo() 正在按预期执行。 api.bar() 可以在 Python 上执行,但在 JavaScript 中,我发布的错误会被抛出。

【问题讨论】:

  • 请提供一个完整的示例,正​​如 Nathan Binkert 在您引用的答案中所做的那样。如果没有有效的示例,读者不得不浪费大量时间尝试重现问题。
  • 你当然是对的 - 我已经添加了我目前正在使用的 sn-ps

标签: javascript c++ swig stdmap


【解决方案1】:

我看起来swig (3.0.12) 的当前版本没有内置支持将 JavaScript 对象或原语映射到 map。我认为您将不得不编写自己的转换器,该转换器接受一个 JavaScript 对象并将其转换为 C++ map。请参阅 this article 以获得一些帮助。

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2012-07-24
    • 2016-10-15
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多