[英]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.