如何使用 ctypes 将此 Python 对象移动到 C++ 中?

How can I move this Python object into C++ using ctypes?

这是一个更大问题的一小部分,但我有一个 C++ class,我正在 python 中初始化它,当我尝试将对象从 [=24= 传递回 C++ 时], none 个初始化值进行转换。

原来的class来自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 0 0 0

我不确定我会给你最好的答案,我不检查它(这只是根据经验)。

首先我会写 return 类型的 Atom Init,只是为了确定。

lib.Atom_init.restype = ctypes.c_void_p

然后我会在有外化的地方写C++代码

void py_print_atom(Atom * atom){print_atom(*atom);}

最后更改 python 代码。

print_atom = wrap_function(lib, 'py_print_atom', None, [ctypes.c_void_p]) 

通过这种方式,我很确定它会起作用。这就是我外部化 C++ 函数的方式。如果您不想手动操作,您也可以使用 Boost::Python(但我想您知道 :D)。

希望对您有所帮助。