boostpython:指针被设置为null

boostpython:指针被设置为null,python,c++,pointers,boost,null,Python,C++,Pointers,Boost,Null,我正在编译以下文件BoostTest.cpp,以便在Python中使用 #define BOOST_PYTHON_STATIC_LIB #include <boost/python.hpp> #include <iostream> #include <cstdio> struct MyStruct { int* a; int* b; }; MyStruct *MyFunction() { int a = 2; int b =

我正在编译以下文件BoostTest.cpp,以便在Python中使用

#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
#include <iostream>
#include <cstdio>

struct MyStruct
{
    int* a;
    int* b;
};

MyStruct *MyFunction()
{
    int a = 2;
    int b = 34;
    MyStruct myStruct = { &a, &b };
    printf("Address of a: %p\n", ((&myStruct)->a));
    printf("Address of b: %p\n", ((&myStruct)->b));
    printf("Address of myStruct: %p\n", &myStruct);
    return &myStruct;
}

void MyTest(MyStruct *myStruct)
{
    printf("Address of a: %p\n", (myStruct->a));
    printf("Address of b: %p\n", (myStruct->b));
    printf("Address of myStruct: %p\n", myStruct);
}

void TestFunc()
{
    MyStruct *myStruct = MyFunction();
    MyTest(myStruct);
}

BOOST_PYTHON_MODULE(BoostTest)
{
    using namespace boost::python;
    class_<MyStruct>("MyStruct");
    def("MyFunction", MyFunction, return_value_policy<manage_new_object>());
    def("MyTest", MyTest);
    def("TestFunc", TestFunc);
}

问题很清楚:当我在python代码中返回MyStruct时,指向a和b的指针丢失,如MyTest()所示。这在运行TestFunc()时不会发生,因此我认为错误一定是在我使用Boost时发生的。我是Boost(和c++)的新手,因此任何帮助都将不胜感激。

看起来这不是一个Boost问题。更重要的是,您在此处使用指向堆栈分配的局部变量的指针:

int a = 2;
int b = 34;
MyStruct myStruct = { &a, &b };

过去这个函数的结尾是我们C++人所称的未定义行为,因为<代码> < <代码> > <代码> b>代码>不再在范围内。 有关更多信息,请参阅。

的可能重复项
int a = 2;
int b = 34;
MyStruct myStruct = { &a, &b };