Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C+的SWIG包装器正确处理向量成员的gc+;用python 我们使用SWIG来封装C++中的类,并在Python中使用它们。我们有一个C++方法,返回一个包含自定义类对象的向量,比如说Foo。因此,基本上,我们使用SWIG包装了以下方法: std::vector<Foo> my_cpp_method(char *);_C++_Vector_Swig - Fatal编程技术网

使用C+的SWIG包装器正确处理向量成员的gc+;用python 我们使用SWIG来封装C++中的类,并在Python中使用它们。我们有一个C++方法,返回一个包含自定义类对象的向量,比如说Foo。因此,基本上,我们使用SWIG包装了以下方法: std::vector<Foo> my_cpp_method(char *);

使用C+的SWIG包装器正确处理向量成员的gc+;用python 我们使用SWIG来封装C++中的类,并在Python中使用它们。我们有一个C++方法,返回一个包含自定义类对象的向量,比如说Foo。因此,基本上,我们使用SWIG包装了以下方法: std::vector<Foo> my_cpp_method(char *);,c++,vector,swig,C++,Vector,Swig,基本上,只要my_list设置为None,向量就会与其内容一起被垃圾收集。当我说o=my_list[0]时,我希望通过在Foo上使用copy构造函数,我可以得到my_list[0]的内容副本(不是用python,但我希望swig能帮我做到这一点),因此将list设置为None不会给我留下悬空的指针 有没有一种方法可以强制SWIG总是在Foo上调用copy构造函数,并在访问列表(作为包装向量)成员时返回一个副本,这样我就可以像普通python列表一样理智地使用my\u cpp\u方法返回的列表,而

基本上,只要my_list设置为None,向量就会与其内容一起被垃圾收集。当我说
o=my_list[0]
时,我希望通过在Foo上使用copy构造函数,我可以得到
my_list[0]
的内容副本(不是用python,但我希望swig能帮我做到这一点),因此将list设置为None不会给我留下悬空的指针

有没有一种方法可以强制SWIG总是在Foo上调用copy构造函数,并在访问列表(作为包装向量)成员时返回一个副本,这样我就可以像普通python列表一样理智地使用
my\u cpp\u方法
返回的列表,而不必担心指针悬空

编辑:关于在python中迭代SWIG包装的向量的有趣发现。我只是想提到这一点,因为SWIG似乎确实提供了一种创建副本的方法,而不是在您使用[]操作符直接访问时。 PS:我们将此作为上述问题的解决方法,但我希望有人能提供一种更健壮、语义更正确/干净的方法来处理SWIG

再次考虑与上面相同的设置。

my_list = wrapper.my_cpp_method()
my_list[0].value = 1
print my_list[0].value  # prints 1
for o in my_list:
  o.value = 10  # Here o is actually a copy of the object and not the actual reference
# The following is very counter-intuitive in "pythonic" sense
print my_list[0].value  # still prints 1
my_list = wrapper.my_cpp_method()
o = my_list[0]

# The following works as expected
print o.value  # assume class Foo has a property called value

# Now the issue
my_list = None
gc.collect()
print o.value  # prints garbage
my_list = wrapper.my_cpp_method()
my_list[0].value = 1
print my_list[0].value  # prints 1
for o in my_list:
  o.value = 10  # Here o is actually a copy of the object and not the actual reference
# The following is very counter-intuitive in "pythonic" sense
print my_list[0].value  # still prints 1