简体   繁体   中英

Swig: Pass a vector<float> from c++ to python

I want to write some code in C++ which returns a vector to python. I tried the following example, but it returns the following object.

<Swig Object of type 'std::vector< float > *' at 0x100331f90>

How can I convert this to a list so that I can use it in python?

My code:

/* File: example.i */
%module example

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

std::vector<float> Test(int n);

.

/* File: example.cpp */

#include <vector>

std::vector<float> Test(int n){

    std::vector<float> a(4);
    a[1] =  1;
    a[2] = 24234;
    return a;
}

.

/* File: example.h 
http://www.swig.org/Doc1.3/Python.html#Python_nn4
*/

#include <vector>
std::vector<float> Test(int n);

I found an answer to this problem. It was kind of hard to find the right keywords for this problems.

The solution is explained here .

%include <std_vector.i> //Takes care of vector<type>

What's still missing are the following three lines

namespace std
{
    %template(FloatVector) vector<float>;
}

In total my example.i now looks like this:

/* File: example.i */
%module example
%include "std_vector.i"

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

namespace std
{
  %template(FloatVector) vector<float>;
}


std::vector<float> Test(int n);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM