简体   繁体   English

python - C++ 嵌入式解释器和对象

[英]python - c++ embedded interpreter and objects

I have a simple C++ program that starts an embedded python intepreter, imports a module and instantiates a class defined in that module.我有一个简单的 C++ 程序,它启动一个嵌入式 python 解释器,导入一个模块并实例化在该模块中定义的类。

I want to understand why the address of the python object (from the python point of view) and the address of the C++ object are different.我想了解为什么python对象的地址(从python的角度)和C++对象的地址不同。

How are the python instance and the c++ view of that instance different memory addresses? python 实例和该实例的 c++ 视图如何不同的内存地址?

Here's some working code, using pybind11 :这是一些使用pybind11 的工作代码:

#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>

using namespace std;
namespace py = pybind11;

int main()
{
    {
        py::scoped_interpreter guard{};
        py::module m = py::module::import("code");
        py::object o = m.attr("SomeClass")();
        cout << "[C++   ] object lives in " << &o << endl;
    }
    return 0;
}
def message_from_python(*args):
    print('[PYTHON]', *args)


class SomeClass:
    def __init__(self):
        message_from_python(self, 'being created')

    def __del__(self):
        message_from_python(self, 'being deleted')

Compilation, execution and stdout:编译、执行和标准输出:

$ g++ -O3 -Wall -std=c++14 `python3 -m pybind11 --includes` code.cc -o code -lpython3.6m
$ ./code
[PYTHON] <code.SomeClass object at 0x7fb6926f1da0> being created
[C++   ] object lives in 0x7fffbed02588                   
[PYTHON] <code.SomeClass object at 0x7fb6926f1da0> being deleted

If we take a quick look at what a py::object is made of in its declaration here , you can see that the class holds a PyObject * as a protected member (inherited from py::handle ).如果我们快速浏览一下什么是py::object在其声明中提出的在这里,你可以看到类持有PyObject *作为一个受保护的成员(从继承py::handle )。 This pointer contains the address that you see printed out from the python side.这个指针包含你看到的从 python 端打印出来的地址。 If you could access it, you would see that如果你可以访问它,你会看到

cout << o.mptr << endl;

produces the same address that the python shell indicates.产生与 python shell 指示的地址相同的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM