首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用SWIG将C++映射转换为Java映射?

如何使用SWIG将C++映射转换为Java映射?
EN

Stack Overflow用户
提问于 2022-06-17 09:03:56
回答 1查看 87关注 0票数 1

我想在Java中使用下面的C++代码。如何定义从C++ std::map到Java转换的类型地图?

File.h

代码语言:javascript
复制
#pragma once
#include <map>
#include <string>

class A
{
 public:
  std::map<std::string, std::string> GetMap();
};

File.cpp

代码语言:javascript
复制
#include "File.h"
std::map<std::string, std::string> A::GetMap()
{
   std::map<std::string, std::string> f;
   // Code to populate map
   return f;
}

我的类型地图文件如下所示

代码语言:javascript
复制
%module test

%include <std_string.i>
%include <std_wstring.i>
%include <std_map.i>
%include <windows.i>
%include <typemaps.i>
#include <string>

%{
  #include "File.h"
%}

%include <File.h>
EN

回答 1

Stack Overflow用户

发布于 2022-06-17 18:21:40

SWIG要求使用为其生成的包装代码的‘% template %指令来声明每个模板实例。参见C++模板中的SWIG文件

%include <File.h>之前添加以下行

代码语言:javascript
复制
%template() std::map<std::string,std::string>;

下面是完整的代码:

test.h

代码语言:javascript
复制
#pragma once
#include <map>
#include <string>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

class API A {
public:
    std::map<std::string, std::string> GetMap();
};

test.cpp

代码语言:javascript
复制
#include "test.h"

API std::map<std::string, std::string> A::GetMap() {
    return {{"key1","value1"},{"key2","value2"}};
}

test.i

代码语言:javascript
复制
%module test

%{
  #include "test.h"
%}

%include <windows.i>
%include <std_map.i>
%include <std_string.i>
%template() std::map<std::string,std::string>;

%include <test.h>

我不熟悉构建Java扩展,但在上面的代码中没有任何特定于Java的内容,下面是一个为Python构建的演示代码。只要支持std_map.istd_string.i,它就应该适用于Java:

代码语言:javascript
复制
>>> import test
>>> a = test.A()
>>> a.GetMap()
{'key1': 'value1', 'key2': 'value2'}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72656876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档