[英]the memory address of object between python and c++ are not identical
我试图用pybind11在c ++和python中打印同一对象的内存地址,但是我发现从两者返回的内存地址不相同。
C ++方面
class Example {
public:
Example() {std::cout << "constuctor" << this << std::endl;}
~Example() {std::cout << "destructor " << this << std::endl;}
};
class ABC {
public:
static std::unique_ptr<Example> get_example() {
// std::shared_ptr<Example> ptr = std::make_shared<Example>();
std::unique_ptr<Example> ptr = std::make_unique<Example>();
return ptr;
}
};
void init_example(py::module & m) {
py::class_<ABC>(m, "ABC")
.def_static("get_example", &ABC::get_example);
}
蟒蛇边
example = my_module.ABC.get_example()
print (example)
输出
constuctor0x234cd80
<Example object at 0x7f5493c37928>
destructor 0x234cd80
来自c ++的内存地址为0x234cd80,但是python为0x7f5493c37928
任何想法?
我对这个问题的Python方面并不熟悉,但是专注于C ++部分,您没有打印出正确的信息。
std::unique_ptr
的地址与所创建的Example
实例的地址不同,因此值将不同。 如果要打印unique_ptr
要寻址的项目的地址,则需要调用get()
函数。
这是显示差异的完整示例:
#include <memory>
#include <iostream>
class Example {
public:
Example() {std::cout << "constuctor " << this << std::endl;}
~Example() {std::cout << "destructor " << this << std::endl;}
};
class ABC {
public:
static std::unique_ptr<Example> get_example()
{
std::unique_ptr<Example> ptr = std::make_unique<Example>();
return ptr;
}
};
int main()
{
std::unique_ptr<Example> p = ABC::get_example();
std::cout << "The unique_ptr address is: " << &p << std::endl;
std::cout << "The get() function returns: " << p.get() << std::endl;
}
输出:
constuctor 0x555a68bd7c20
The unique_ptr address is: 0x7ffd9fa6c120
The get() function returns: 0x555a68bd7c20
destructor 0x555a68bd7c20
因此,您需要调整Python代码以显示get()
的返回值。
pybind11创建一个Python对象,该对象具有对C ++对象的引用。 因此,Python pybind11包装器和C ++对象的地址不同。
缺省pybind11 str对象表示中的地址是python对象的地址,而不是基础C ++对象或其智能指针的地址。
如果您需要了解C ++对象的地址,请按照@PaulMcKenzie的建议在绑定代码中添加一个方法。
C ++:
namespace py = pybind11;
PYBIND11_MODULE(example_module, m){
m.def("add", add);
py::class_<Example>(m,"Foo")
.def(py::init())
.def("get_raw_address",[](Example& foo){ return reinterpret_cast<uint64_t>(&foo);});
}
蟒蛇:
example = Example()
print(example)
print("C++ address: %x" % example.get_raw_address())
输出:
constuctor 0x10eff20
<example_module.Foo object at 0x7f51c71d4298>
C++ address: 10eff20
destructor 0x10eff20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.