【问题标题】:Swig: Pass a vector<float> from c++ to pythonSwig:将向量 <float> 从 c++ 传递给 python
【发布时间】:2015-10-12 13:07:45
【问题描述】:

我想用 C++ 编写一些代码,将向量返回给 python。我尝试了以下示例,但它返回了以下对象。

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

如何将其转换为列表以便在 python 中使用?

我的代码:

/* 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);

【问题讨论】:

  • 我没有用过python,但是尝试在接口文件中添加%include &lt;std_vector.i&gt;
  • 谢谢,我试过了,但没有任何改变。

标签: python swig


【解决方案1】:

我找到了这个问题的答案。为这个问题找到合适的关键字有点困难。

解决方案解释here

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

还缺少以下三行

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

总的来说,我的 example.i 现在看起来像这样:

/* 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);

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 1970-01-01
    • 2021-11-03
    • 2020-10-09
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多