首页 > 解决方案 > 如何使 std::map 在 swig 中保存不同的数据类型?

问题描述

我怎样才能让 这张地图deque<map<char, int>> fp(vector<int> inp_list)deque<map<char, any>> fp哪里any存储整数、字符串和数组列表。我知道在 c++ 17 中存在一些解决方案我可以使用此链接中给出的 Any但如何将它与 swig 接口?我找不到有人在 swig 中将 map 用于不同数据类型的任何参考。

f_pi:

%module f_p
#define SWIGPYTHON_BUILTIN

%{
  #include "numpy/arrayobject.h"
  #define SWIG_FILE_WITH_INIT  /* To import_array() below */
  #include "f_p.h"
%}

%include "std_map.i"
%import "std_deque.i" 
// %include "numpy.i"
%import "std_vector.i" 

#include <deque>

%template() std::vector<int>;

%template (map) std::map<char,int>;
%template(MapDeque) std::deque<std::map<char, int>>;

%typemap(ret) std::deque<std::map<char, int>> {
  $result = PyTuple_New($1.size());
  for (int i = 0; i < (int)$1.size(); ++i)
    PyTuple_SetItem($result, i, swig::traits_from<std::map<char, int>>::asdict($1[i]));
}


%include "f_p.h"

f_p.cpp:

#include <deque> 
#include <iostream> 
using namespace std; 

#include <vector>
#include <map>  

deque<map<char, int>> fp(vector<int> inp_list) 
{
    map<char, int> my_map = {
    { 'A', 1 },
    { 'B', 2 },
    { 'C', 3 }
    };
    deque<map<char, int>> mydeque;
    mydeque.push_back(my_map); 
    return mydeque;
}

f_p.h:

#ifndef F_P_H
#define f_P_H
#include <stdio.h>
#include <deque>
#include <map>
#include <vector>

/* Define function prototype */
std::deque<std::map<char, int>> fp(std::vector<int> inp_list) ;
#endif

构建.sh:

rm *.o f_p_wrap.cpp _f_p.so f_p.py
rm -rf __pycache__

g++ -O3 -march=native -fPIC -c f_p.cpp

swig -python -c++ -o f_p_wrap.cpp f_p.i

# Next, compile the wrapper code:

g++ -O3 -march=native -w -fPIC -c $(pkg-config --cflags --libs python3) -I /home/kriti/anaconda3/lib/python3.7/site-packages/numpy/core/include f_p.cpp f_p_wrap.cpp

g++ -std=c++11 -O3 -march=native -shared f_p.o f_p_wrap.o -o _f_p.so -lm

标签: c++c++11swig

解决方案


推荐阅读