Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Python对象到C++;指针问题_C++_Python_Boost_Boost Python_Embedded Language - Fatal编程技术网

C++ Python对象到C++;指针问题

C++ Python对象到C++;指针问题,c++,python,boost,boost-python,embedded-language,C++,Python,Boost,Boost Python,Embedded Language,这是我的第一篇帖子:)。我可以将Python扩展对象转换成C++指针,但我有一个问题。首先,我将向您展示我的代码,然后我将解释问题 这是我的班级: #include <boost/python.hpp> using namespace boost::python; class Base { public: virtual const char* HelloWorld() = 0; }; class BaseWrapper : public Base, pub

这是我的第一篇帖子:)。我可以将Python扩展对象转换成C++指针,但我有一个问题。首先,我将向您展示我的代码,然后我将解释问题

这是我的班级:

#include <boost/python.hpp>


using namespace boost::python;


class Base
{

public:

    virtual const char* HelloWorld() = 0;

};


class BaseWrapper : public Base, public wrapper<BaseWrapper>
{

public:

    virtual const char* HelloWorld()
    {

        if (override f = this->get_override("HelloWorld"))
            return call<const char*>(f.ptr());

        return "FAILED TO CALL";

    }

};
和主文件:

int main() 
{

     // Start the interpreter.
     Py_Initialize();

     // Import the module that we need (hello.py)
     object module = import("hello");

     // Get a C++ pointer of the derived python class.
     Base* base = extract< Base* >( module.attr("NewDerived")() );

     // Call the HelloWorld function
     std::cout << base->HelloWorld() << std::endl;

}
然后,当我再次运行我的应用程序时,它崩溃了,因为我在以下行中出错:

std::cout << base->HelloWorld() << std::endl;

你觉得怎么样?

最后,另一位程序员向我解释了解决方案

我不知道它最初为什么工作,但问题是,在我尝试调用成员函数之前,对象正在被销毁。我需要将提取调用分成两部分,如下所示:

object derived = module.attr("NewDerived")();
Base* base = extract< Base* >( derived );
object-derived=module.attr(“NewDerived”)();
Base*Base=提取(派生);
这将使对象保持足够长的时间,以便我实际调用其上的函数

def NewDerived():
    import hello_ext

    class Derived(hello_ext.BaseWrapper):
        def __init__(self):
                super(Derived, self).__init__()
        def HelloWorld(self):
                return "This is a Hello" # I CHANGED THIS LINE!!!!

    return Derived()
std::cout << base->HelloWorld() << std::endl;
inline api::object_base::~object_base()
{
    Py_DECREF(m_ptr);
}
object derived = module.attr("NewDerived")();
Base* base = extract< Base* >( derived );