gpt4 book ai didi

javascript - 如何使用 Swig 将 JavaScript 中的关联数组映射到 C++ 中的字符串映射?

转载 作者:可可西里 更新时间:2023-11-01 15:23:51 28 4
gpt4 key购买 nike

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

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

对于 Python 来说,为 map 创建一个别名就足够了:

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 中会抛出我发布的错误。

最佳答案

我看起来像当前版本的 swig (3.0.12) 没有内置支持将 JavaScript 对象或基元映射到 map。我认为您必须编写自己的转换器,它接受 JavaScript 对象并将其转换为 C++ map。参见 this article寻求一点帮助。

关于javascript - 如何使用 Swig 将 JavaScript 中的关联数组映射到 C++ 中的字符串映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53664459/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com