这是一个较大问题的一小部分,但我有一个C++类,我在Python中初始化,当我试图从Python中把对象传递回C++时,没有初始化的值进行转换。你知道吗
原始类是C++的,它是用Python初始化的,当我试图把初始化的对象移回C++时,问题就出现了。你知道吗
Python代码
from ctypes import c_int, c_double, CDLL, Structure
lib = CDLL('./libDftConfig.so')
class Atom(Structure):
_fields_ = [('type_', c_int), ('x_', c_double),
('y_', c_double), ('z_', c_double)]
# Using C++ class
def __init__(self, t, x, y, z):
self.obj = lib.Atom_init(t, x, y, z)
def wrap_function(lib, funcname, restype, argtypes):
func = lib.__getattr__(funcname)
func.restype = restype
func.argtypes = argtypes
return func
# wrap the C++ function
print_atom = wrap_function(lib, 'py_print_atom', None, [Atom])
# Initialize C++ class and pass it back to C++ here
print_atom(Atom(50,5,10,15))
C++代码
#include <iostream>
struct Atom {
public:
Atom(int type, double x, double y, double z) : type_(type), x_(x), y_(y), z_(z) {}
int type_;
double x_;
double y_;
double z_;
};
std::ostream& operator<<(std::ostream &strm, const Atom &atom) {
return strm << atom.type_ << " " << atom.x_ << " " << atom.y_ << " " << atom.z_ << std::endl;
}
void print_atom(Atom atom)
{
std::cout << atom << std::endl;
}
extern "C"
{
Atom* Atom_init(int type, double x, double y, double z)
{
return new Atom(type, x, y, z);
}
void py_print_atom(Atom atom){print_atom(atom);}
}
期望值:50 5 10 15
实际值:0
我不确定我是否会给你最好的答案,我也不核实(这只是凭经验)。你知道吗
首先,我将编写Atom Init的返回类型,只是为了确定。你知道吗
然后我将在C++代码中编写,其中有外部化
最后修改python代码。你知道吗
这样的话,我很肯定它会成功的。这就是我如何将C++函数外化。如果您不想手工操作,也可以使用Boost::Python(但我猜您知道:D)。你知道吗
希望对你有帮助。你知道吗
相关问题 更多 >
编程相关推荐