我尝试重做此处显示的内容,但有些东西不起作用,我看不到什么。
我们有一个包含此方法的 C++ 类(“Point”):
int Point::myfunc(int a, std::vector<float> *b)
{
for (short int i = 0; i <= 10; i = i + 1)
b->push_back(static_cast<float>(a * i));
return 0;
}
我有 SWIG 的接口文件“.i”:
%module Point
%{
#include "Point.h"
%}
%include <std_string.i>
// Define typemaps for std::vector<float>*
%typemap(in) std::vector<float>* (std::vector<float> tmp) {
$1 = &tmp;
}
%typemap(argout) std::vector<float>* {
// Nothing needed here; the vector is modified in-place.
}
%include "Point.h"
我生成了Python模块(swig -c++ -python -Wall Point.i),但是当我像这样使用它时:
a_list= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b=A.myfunc(3,a_list)
print (b)
我获得 b 的“0”(我期待修改后的列表)。你能告诉我我做错了什么吗?预先感谢。
向量是如何就地修改的?您创建一个名为
tmp
的新变量,并将 $1
分配给它的地址。这会为参数分配一个新值,它本质上是一个局部变量。
不要重新发明轮子,使用 SWIG 内置函数的示例中有一些非常相似的东西,您不必创建新的类型映射:
%module Point
%include stl.i
// We need to tell SWIG that we are instantiating std::vector for float
%template(FloatVector) std::vector<float>;
// There is a standard INOUT SWIG typemap for doing what you need
%apply std::vector<float> *INOUT { std::vector<float> *b };
%inline %{
#include <vector>
int myfunc(int a, std::vector<float> *b)
{
for (short int i = 0; i <= 10; i = i + 1)
b->push_back(static_cast<float>(a * i));
return 0;
}
%}