简体   繁体   English

Python中的SWIG C ++矢量访问

[英]SWIG c++ vector access in python

This may be a noob question but here it goes. 这可能是一个菜鸟问题,但这是正确的。 I have wrapped a 3d vector into a python module using SWIG. 我已经使用SWIG将3d向量包装到python模块中。 Everything has compiled and I can import the module and perform actions with it. 一切都已编译,我可以导入模块并对其执行操作。 I can't seem to figure out how to access my vector in python to store and change values in it. 我似乎无法弄清楚如何在python中访问矢量来存储和更改其中的值。 How do I store and change my vector values in python. 如何在python中存储和更改矢量值。 My code is below and was written to test if the algorithm stl works with SWIG. 我的代码在下面,用于测试算法stl是否与SWIG配合使用。 It does seem to work but I need to be able to put values into my vector with python. 它似乎确实有效,但是我需要能够使用python将值放入向量中。

header.h 头文件

 #ifndef HEADER_H_INCLUDED

 #define HEADER_H_INCLUDED

 #include <vector>

 using namespace std;

 struct myStruct{

 int vecd1, vecd2, vecd3;

 vector<vector<vector<double> > >vec3d;

 void vecSizer();
 void deleteDuplicates();
 double vecSize();
 void run();
 };

 #endif // HEADER_H_INCLUDED

main.cpp main.cpp

 #include "header.h"
 #include <vector>
 #include <algorithm>

 void myStruct::vecSizer()
 {
     vec3d.resize(vecd1);

     for(int i = 0; i < vec3d.size(); i++)
     {
         vec3d[i].resize(vecd2);

         for(int j = 0; j < vec3d[i].size(); j++)
         {
             vec3d[i][j].resize(vecd3);
         }
     }
 }

 void myStruct::deleteDuplicates()
 {
     vector<vector<vector<double> > >::iterator it;
     sort(vec3d.begin(),vec3d.end());
     it = unique(vec3d.begin(),vec3d.end());
     vec3d.resize(distance(vec3d.begin(), it));
 }

 double myStruct::vecSize()
 {
     return vec3d.size();
 }

 void myStruct::run()
 {
     vecSizer();
     deleteDuplicates();
     vecSize();
 }

from the terminal (Ubuntu) 从终端(Ubuntu)

 import test #import the SWIG generated module
 x = test.myStruct() #create an instance of myStruct
 x.vecSize() #run vecSize() should be 0 since vector dimensions are not initialized
 0.0 
 x.vec3d #see if vec3d exists and is of the correct type
 <Swig Object of type 'vector< vector< vector< double > > > *' at       0x7fe6a483c8d0>

Thanks in advance! 提前致谢!

It turns out that vectors are converted to immutable python objects when the wrapper/interface is generated. 事实证明,在生成包装器/接口时,矢量会转换为不可变的python对象。 So in short you cannot modify wrapped c++ vectors from python. 简而言之,您不能从python修改包装的c ++向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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