【发布时间】:2019-04-11 06:43:30
【问题描述】:
我正在使用 SWIG 从 Python 接受大小可变的列表,将其发送到 C++ 以对其进行处理,然后将其发送回 Python 以打印出来。
我是 Python、C++ 和 Swig 的新手。目前,发送的列表将在我的 C++ 函数中作为向量参数处理。之后,函数返回的是一个指针,它由“out”类型映射处理。
列表可以从 Python 中显示,但前提是在输出类型映射中设置了大小。目前我需要让它处理各种大小的列表。
当尝试实现这一点时,我最终会返回地址而不是 Python 中的列表。
下面展示了在给定固定大小时有效的代码。
customvector.cc
#include "customvector.h"
#include <algorithm>
#include <functional>
float * summy(std::vector<float> a)
{
float * p = a.data();
return p;
}
customvector.h
#include <stdio.h>
#include <iostream>
#include <vector>
float * summy(std::vector<float> a);
customvector.i
/* File: customvector.i */
%module customvector
%{
#define SWIG_FILE_WITH_INIT
#include "customvector.h"
%}
%include "std_vector.i"
%include <stdint.i>
namespace std {
%template(Line) vector < float >;
}
%typemap(out) float* summy{
int i;
$result = PyList_New(3);
for (i = 0; i < 3; i++) {
PyObject *o = PyFloat_FromDouble((double) $1[i]);
PyList_SetItem($result,i,o);
}
}
float * summy(std::vector<float> a);
我的python结果:
>>> import customvector
>>> a = [1,2,3]
>>> customvector.summy(a)
[1.0, 2.0, 3.0]
然后我编辑了我的接口文件,以便输出类型映射现在使用 [ANY] 而不是仅 3 以允许长度变化。
编辑 customvector.i
/* File: customvector.i */
%module customvector
%{
#define SWIG_FILE_WITH_INIT
#include "customvector.h"
%}
%include "std_vector.i"
%include <stdint.i>
namespace std {
%template(Line) vector < float >;
}
%typemap(out) float* summy [ANY]{ //changed from 3 to [ANY]
int i;
$result = PyList_New($1_dim0); //changed from 3 to $1_dim0
for (i = 0; i < $1_dim0; i++) {
PyObject *o = PyFloat_FromDouble((double) $1[i]);
PyList_SetItem($result,i,o);
}
}
float * summy(std::vector<float> a);
Python 的结果:
>>> import customvector
>>> a = [1,2,3]
>>> customvector.summy(a)
<Swig Object of type 'float *' at 0x000001E4E32E6420>
这不是我想要的,它应该显示之前显示的内容。
我尝试按照此处某处列出的文档进行操作:http://www.swig.org/Doc2.0/Typemaps.html#Typemaps_nn40 让 SWIG 获得比输出的值,但它似乎不起作用。
我也遇到了这个允许长度变化的解决方案:Python/SWIG: Output an array 但我不确定它是如何工作的,因为我尝试使用它,但代码无法编译(说没有定义 Templen)。
如何从 C++ 输出到 python 中这样一个可变大小的数据?
【问题讨论】:
-
由于您的函数按值获取向量,因此当您尝试使用返回的指针时,您的行为未定义。您还需要让函数的调用者知道数组的实际大小。
-
无论如何,[ANY] 类型映射在这里不是正确的选择,因为在编译时不知道大小,因此不会被应用。
-
这是否意味着我需要计算 cc 文件中向量的大小,然后将其传递给接口文件以确定它有多大?