How to convert C++ map to Java map using SWIG?

205 Views Asked by At

I would like to SWIG below C++ code to be used in Java. How can i define a typemap to convert from C++ std::map to Java map?

File.h

#pragma once
#include <map>
#include <string>

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

File.cpp

#include "File.h"
std::map<std::string, std::string> A::GetMap()
{
   std::map<std::string, std::string> f;
   // Code to populate map
   return f;
}

My typemap file looks as below

%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>
1

There are 1 best solutions below

0
Mark Tolonen On

SWIG requires each template instance to be declared using the `%template% directive for wrapper code to be generated for it. See C++ templates in the SWIG documentation.

Add the following line before %include <File.h>:

%template() std::map<std::string,std::string>;

Here's the full code:

test.h

#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

#include "test.h"

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

test.i

%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>

I'm not familar with building a Java extension, but there is nothing Java-specific in the above code so below is a demo with the above code built for Python. It should work for Java as long as the support for std_map.i and std_string.i is there:

>>> import test
>>> a = test.A()
>>> a.GetMap()
{'key1': 'value1', 'key2': 'value2'}