我想在Java中使用下面的C++代码。如何定义从C++ std::map到Java转换的类型地图?
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;
}我的类型地图文件如下所示
%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>发布于 2022-06-17 18:21:40
SWIG要求使用为其生成的包装代码的‘% template %指令来声明每个模板实例。参见C++模板中的SWIG文件。
在%include <File.h>之前添加以下行
%template() std::map<std::string,std::string>;下面是完整的代码:
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>我不熟悉构建Java扩展,但在上面的代码中没有任何特定于Java的内容,下面是一个为Python构建的演示代码。只要支持std_map.i和std_string.i,它就应该适用于Java:
>>> import test
>>> a = test.A()
>>> a.GetMap()
{'key1': 'value1', 'key2': 'value2'}https://stackoverflow.com/questions/72656876
复制相似问题