[英]How can I move this Python object into C++ using ctypes?
這是一個較大問題的一小部分,但是我有一個正在用python初始化的C ++類,當我嘗試將對象從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 0 0 0
我不確定我會給你最好的答案,而且我不檢查(這只是憑經驗)。
首先,我要確定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)。
希望對您有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.