我尝试用Pixg绑定Python中的C++模板。 我希望我的字体名可以是浮点数或双精度。 我用3.0.8瑞士法郎
这是我的C++模板:人事管理.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
我的个人管理.cpp只包含: #包括“人事管理.hpp““
这是我的接口文件:Personnage.i
^{pr2}$我使用以下行来使用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确实包含一个float。在
我不知道我会把事情搞砸。在
感谢您抽出时间!在
感谢您的时间和您的回答!在
Python只知道double,因此返回的float将被转换为double,并且附加的数字将只是未初始化的内存,但是当您打印值时,这些也会被考虑在内。在
您甚至不需要一个复杂的SWIG和Python示例来重现这一点。只需从double初始化一个float(literal
^{pr2}$1.59
是double)并用double精度打印它。在相关问题 更多 >
编程相关推荐