Python 中 C++ class 与 SWIG 的奇怪行为
Strange behaviour of C++ class in Python with SWIG
我在 C++ 中有一个 class,有两种方法(大型项目的一部分)。这些方法做的工作非常相似:第一个规范化向量并 returns 它,而第二个 returns 规范化向量而不改变原始向量。
vector3.h
:
class Vector3
{
public:
Vector3(double a = 0.0, double b = 0.0, double c = 0.0)
: x(a), y(b), z(c) {}
Vector3(const Vector3& other) : x(other.x), y(other.y), z(other.z) {}
double length() const { return sqrt(x*x+y*y+z*z); }
Vector3& normalize()
{
float_type n = length();
n = float_type(1.0) / ( n ? n : 1.0 );
this->x *= n;
this->y *= n;
this->z *= n;
return *this;
}
Vector3 normalized() const
{
Vector3 v(*this);
v.normalize();
return v;
}
std::string toString()
{
std::ostringstream strm;
strm << '(' << x << ", " << y << ", " << z << ')' ;
return strm.str();
}
Vector3 operator+(const Vector3& other) const
{
return Vector3(x + other.x, y + other.y, z + other.z);
}
private:
double x,y,z;
};
我使用 SWIG(通过 cmake)为此 class 构建了 Python 绑定。
vector3.i
:
%include <stl.i>
%include <carrays.i>
%include <cpointer.i>
%module vectortest
%{
#include "vector3.h"
%}
%include "vector3.h"
CMakeLists.txt
:
cmake_minimum_required(VERSION 2.8)
add_executable("vtest" "vtest.cpp")
find_package(SWIG)
include(${SWIG_USE_FILE})
find_package(PythonLibs)
find_package(PythonInterp)
include_directories(${CMAKE_SOURCE_DIR})
include_directories(${PYTHON_INCLUDE_DIRS})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(SOURCE vector3.i PROPERTIES CPLUSPLUS ON)
SWIG_ADD_MODULE(vectortest_python python vector3.i )
SWIG_LINK_LIBRARIES(vectortest_python ${PYTHON_LIBRARIES} ${LIBS})
set_target_properties(_vectortest_python PROPERTIES PREFIX "_" OUTPUT_NAME "vectortest")
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "from distutils.sysconfig import get_python_lib; print (get_python_lib())" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE)
install(TARGETS ${SWIG_MODULE_vectortest_python_REAL_NAME} DESTINATION ${PYTHON_SITE_PACKAGES})
install(FILES ${CMAKE_BINARY_DIR}/vectortest.py DESTINATION ${PYTHON_SITE_PACKAGES})
C++ 中的行为很好。
vtest.cpp
:
#include <iostream>
#include "vector3.h"
int main()
{
Vector3 v1(1,0,0);
Vector3 v2(0,1,0);
std::cout << (v1+v2).toString() << std::endl;
std::cout << (v1+v2).normalized().toString() << std::endl;
std::cout << (v1+v2).normalize().toString() << std::endl;
return 0;
}
输出:
(1, 1, 0)
(0.707107, 0.707107, 0)
(0.707107, 0.707107, 0)
然而,它在 Python 中的行为很奇怪:
vtest.py
:
#!/usr/bin/python3
from vectortest import Vector3
v1 = Vector3(1,0,0)
v2 = Vector3(0,1,0)
print( (v1+v2).toString() )
print( (v1+v2).normalized().toString() )
print( (v1+v2).normalize().toString() )
输出:
(1, 1, 0)
(0.707107, 0.707107, 0)
(0, 0.707107, 0)
第二种方法 (normalized()
) 按预期工作,但第一种 (normalize()
) 没有。是什么原因造成的?有关如何解决此问题的任何建议?
@donkopotamus 和@JensMunk 是对的。
您的 代码在 Python 中不正确,因为临时变量的生命周期不同。
C++ 临时变量 (v1+v2) 的生命周期是 C++ 中函数调用的整个序列。 Python 通过 SWIG 包装器为每个函数调用进行调用,即通过 distinct Python 对象。对于 Python:
(v1+v2) - 构造了一个临时 Python 对象 (tp1 = v1 + v2),其生命周期与调用顺序不同。
(v1+v2).normalized() - 产生另一个临时 Python 对象 (tp2_1);
(v1+v2).normalize() - 产生另一个临时 Python 对象 (tp2_2) 内部引用第一个临时 Python 对象 (tp1 ).
临时 Python 对象 (tp1 =
v1 + v2) 递减引用计数器,现在可以进行垃圾回收,使 tp2_2 的内容 无效。
(v1+v2).normalized().toString() - 产生一个临时的 Python 对象 (tp3_1) 由有效的 tp2_1, tp2_1现在可以进行垃圾回收了;
(v1+v2).normalize().toString() - 从可能 corrupted tp2_2[ 产生一个临时 Python 对象 (tp3_2) =23=]
...
我在 C++ 中有一个 class,有两种方法(大型项目的一部分)。这些方法做的工作非常相似:第一个规范化向量并 returns 它,而第二个 returns 规范化向量而不改变原始向量。
vector3.h
:
class Vector3
{
public:
Vector3(double a = 0.0, double b = 0.0, double c = 0.0)
: x(a), y(b), z(c) {}
Vector3(const Vector3& other) : x(other.x), y(other.y), z(other.z) {}
double length() const { return sqrt(x*x+y*y+z*z); }
Vector3& normalize()
{
float_type n = length();
n = float_type(1.0) / ( n ? n : 1.0 );
this->x *= n;
this->y *= n;
this->z *= n;
return *this;
}
Vector3 normalized() const
{
Vector3 v(*this);
v.normalize();
return v;
}
std::string toString()
{
std::ostringstream strm;
strm << '(' << x << ", " << y << ", " << z << ')' ;
return strm.str();
}
Vector3 operator+(const Vector3& other) const
{
return Vector3(x + other.x, y + other.y, z + other.z);
}
private:
double x,y,z;
};
我使用 SWIG(通过 cmake)为此 class 构建了 Python 绑定。
vector3.i
:
%include <stl.i>
%include <carrays.i>
%include <cpointer.i>
%module vectortest
%{
#include "vector3.h"
%}
%include "vector3.h"
CMakeLists.txt
:
cmake_minimum_required(VERSION 2.8)
add_executable("vtest" "vtest.cpp")
find_package(SWIG)
include(${SWIG_USE_FILE})
find_package(PythonLibs)
find_package(PythonInterp)
include_directories(${CMAKE_SOURCE_DIR})
include_directories(${PYTHON_INCLUDE_DIRS})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(SOURCE vector3.i PROPERTIES CPLUSPLUS ON)
SWIG_ADD_MODULE(vectortest_python python vector3.i )
SWIG_LINK_LIBRARIES(vectortest_python ${PYTHON_LIBRARIES} ${LIBS})
set_target_properties(_vectortest_python PROPERTIES PREFIX "_" OUTPUT_NAME "vectortest")
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "from distutils.sysconfig import get_python_lib; print (get_python_lib())" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE)
install(TARGETS ${SWIG_MODULE_vectortest_python_REAL_NAME} DESTINATION ${PYTHON_SITE_PACKAGES})
install(FILES ${CMAKE_BINARY_DIR}/vectortest.py DESTINATION ${PYTHON_SITE_PACKAGES})
C++ 中的行为很好。
vtest.cpp
:
#include <iostream>
#include "vector3.h"
int main()
{
Vector3 v1(1,0,0);
Vector3 v2(0,1,0);
std::cout << (v1+v2).toString() << std::endl;
std::cout << (v1+v2).normalized().toString() << std::endl;
std::cout << (v1+v2).normalize().toString() << std::endl;
return 0;
}
输出:
(1, 1, 0)
(0.707107, 0.707107, 0)
(0.707107, 0.707107, 0)
然而,它在 Python 中的行为很奇怪:
vtest.py
:
#!/usr/bin/python3
from vectortest import Vector3
v1 = Vector3(1,0,0)
v2 = Vector3(0,1,0)
print( (v1+v2).toString() )
print( (v1+v2).normalized().toString() )
print( (v1+v2).normalize().toString() )
输出:
(1, 1, 0)
(0.707107, 0.707107, 0)
(0, 0.707107, 0)
第二种方法 (normalized()
) 按预期工作,但第一种 (normalize()
) 没有。是什么原因造成的?有关如何解决此问题的任何建议?
@donkopotamus 和@JensMunk 是对的。
您的 代码在 Python 中不正确,因为临时变量的生命周期不同。
C++ 临时变量 (v1+v2) 的生命周期是 C++ 中函数调用的整个序列。 Python 通过 SWIG 包装器为每个函数调用进行调用,即通过 distinct Python 对象。对于 Python:
(v1+v2) - 构造了一个临时 Python 对象 (tp1 = v1 + v2),其生命周期与调用顺序不同。
(v1+v2).normalized() - 产生另一个临时 Python 对象 (tp2_1);
(v1+v2).normalize() - 产生另一个临时 Python 对象 (tp2_2) 内部引用第一个临时 Python 对象 (tp1 ).
临时 Python 对象 (tp1 =
v1 + v2) 递减引用计数器,现在可以进行垃圾回收,使 tp2_2 的内容 无效。
(v1+v2).normalized().toString() - 产生一个临时的 Python 对象 (tp3_1) 由有效的 tp2_1, tp2_1现在可以进行垃圾回收了;
(v1+v2).normalize().toString() - 从可能 corrupted tp2_2[ 产生一个临时 Python 对象 (tp3_2) =23=]
...