After building and calling it using python main.py
it gives me result like this:
[array([22209328, 21870, 0], dtype=int32), array([24088960, 21870, 1], dtype=int32)]
Why is it happening? I can't find out the bug in my code. I get only the last element of each array correct. rest shows some random number which I assume to be address.
Expected output:
[array([1, 0, 0], dtype=int32), array([2, 1, 1], dtype=int32)]
h_map.cpp
#include <stdio.h>
#include <math.h>
#include <map>
#include <vector>
#include <iostream>
using namespace std;
map<int, vector<int> >hash_map()
{
map<int, vector<int> >dist;
for(int i=0;i<2;i++)
{
dist[i] = {i+1,i,i}; // 1,0,0 2,1,1
// 0 --> 1,2,3,
// 1-> 2,3,4
}
return dist;
}
h_map.h
#ifndef H_MAP_H
#define H_MAP_H
#include <vector>
#include <map>
using namespace std;
map<int, vector<int> >hash_map();
#endif
h_map.i
%module h_map
#define SWIGPYTHON_BUILTIN
%{
#include "numpy/arrayobject.h"
#define SWIG_FILE_WITH_INIT /* To import_array() below */
#include "h_map.h"
%}
%include "std_map.i"
%import "std_vector.i"
%include "numpy.i"
%init %{
import_array();
%}
namespace std {
%template(IntVector) vector<int>;
}
namespace std {
%template (mapiv) std::map<int,vector<int> >;
}
%typemap(out) std::map<int, std::vector<int> >
{
for(auto it:$1)
{
int subLength = it.second.size();
npy_intp dims[1] = {subLength };
PyObject* temp = PyArray_SimpleNewFromData(1, dims, PyArray_INT, it.second.data());
$result = SWIG_Python_AppendOutput($result, temp);
}
}
%include "h_map.h"```
build.sh
g++ -fPIC -c h_map.cpp
swig -python -c++ -o h_map_wrap.cpp h_map.i
g++ -fPIC -c $(pkg-config --cflags --libs python3) -I /home/kriti/anaconda3/lib/python3.7/site-packages/numpy/core/include h_map_wrap.cpp
g++ -shared h_map.o h_map_wrap.o -o _h_map.so -lm
main.py
import numpy as np
from h_map import hash_map
a = hash_map()
print(a)
Aucun commentaire:
Enregistrer un commentaire