我尝试用SWIG在Python中绑定一个C++模板。我希望我的typename T可以是一个浮点型或双精度型。我使用SWIG 3.0.8
这是我的C++模板: Personnage.hpp (不要全部阅读,只有一个函数让我们感兴趣)
#ifndef PERSONNAGE_H_INCLUDED
#define PERSONNAGE_H_INCLUDED
#include <string>
#include <iostream>
#include <sstream>
template <typename T>
class Personnage
{
public:
Personnage();
~Personnage();
void setAge(const int &age);
void setTaille(const T &taille);
int getAge() const;
T getTaille() const;
protected:
std::string P_nom;
int P_age;
T P_taille;
};
template<typename T>
Personnage<T>::Personnage()
: P_nom("Rigoberto"), P_age(42), P_taille(T(1.10))
{
}
template<typename T>
Personnage<T>::~Personnage(){}
template<typename T>
void Personnage<T>::setAge(const int &age)
{
P_age = age;
}
template<typename T>
void Personnage<T>::setTaille(const T &taille)
{
P_taille = taille;
}
template<typename T>
int Personnage<T>::getAge() const
{
return P_age;
}
template<typename T>
T Personnage<T>::getTaille() const
{
return P_taille;
}
#endif // PERSONNAGE_H_INCLUDED
我的包含只包含:# Personnage.cpp "Personnage.hpp“
下面是我的接口文件: Personnage.i
%module Personnage
%{
#include "Personnage.hpp"
%}
%include "Personnage.hpp"
%module Personnage
%{
#include "Personnage.hpp"
%}
%rename (PersonnageD) Personnage::Personnage();
%rename (PersonnageC) Personnage::Personnage(const Personnage<T> &personnage);
%include "Personnage.hpp"
%include "std_string.i"
//constructeurs simples
%template(PFloat) Personnage<float>;
%template(PDouble) Personnage<double>;
%template(estGrand) estGrand<float, float>;
%template(estGrand) estGrand<float, double>;
%template(estGrand) estGrand<double, float>;
%template(estGrand) estGrand<double, double>;
我使用下面这行代码来使用SWIG和编译:
swig -c++ -python Personnage.i
g++ -fPIC -c Personnage.cpp
g++ -fPIC -c Personnage_wrap.cxx $(python-config --cflags)
g++ -shared Personnage.o Personnage_wrap.o $(python-config --ldflags) -o _Personnage.so
下面是我用来测试的python文件:
import Personnage
persSimple = Personnage.PDouble("didier",45,1.59) #Player with a "Taille" in Double
print(persSimple.getTaille())
FpersSimple = Personnage.PFloat("didier",45,1.59) #Player with a "Taille" in Float
print(FpersSimple.getTaille())
第一个印刷品显示"1.59",它是正确的。第二个打印结果显示“1.5900000(随机数)”,这正是我在这里寻求帮助的原因:它应该只显示"1.59“。
当我在Python上输入"FpersSimple“时,我得到:
<Personnage.PFloat; proxy of <Swig Object of type 'Personnage< float > *' at 0x7fd2742b3480> >
所以我的FpersSimple绝对包含了一个浮点数。
我不知道我会在哪里搞砸。
感谢您的宝贵时间!
感谢您的时间和您的答案!
发布于 2018-07-09 07:36:46
Python只知道double,所以您返回的浮点数将被转换为double,附加的数字将只是未初始化的内存,但当您打印该值时,这些也会被考虑在内。
您甚至不需要使用SWIG和Python的复杂示例来重现这一点。只需从double初始化一个浮点型(文字1.59
是double)并以双精度打印它即可。
#include <iomanip>
#include <iostream>
#include <limits>
int main() {
double d = 1.59;
float f = 1.59;
std::cout << std::setprecision(std::numeric_limits<double>::digits10)
<< std::fixed
<< d << '\n'
<< f << '\n';
}
1.590000000000000
1.590000033378601
https://stackoverflow.com/questions/50695733
复制相似问题