Boost Python:指针设置为空



我正在编译以下文件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: %pn", ((&myStruct)->a));
    printf("Address of b: %pn", ((&myStruct)->b));
    printf("Address of myStruct: %pn", &myStruct);
    return &myStruct;
}
void MyTest(MyStruct *myStruct)
{
    printf("Address of a: %pn", (myStruct->a));
    printf("Address of b: %pn", (myStruct->b));
    printf("Address of myStruct: %pn", 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 的输出如下所示:

>>> import BoostTest
>>> x = BoostTest.MyFunction()
Address of a: 0027FBF4
Address of b: 0027FBF0
Address of myStruct: 0027FBE8
>>> BoostTest.MyTest(x)
Address of a: 00000000
Address of b: 00000000
Address of myStruct: 0027FBE8
>>> BoostTest.TestFunc()
Address of a: 0027FC0C
Address of b: 0027FC08
Address of myStruct: 0027FC00
Address of a: 0027FC0C
Address of b: 0027FC08
Address of myStruct: 0027FC00
>>>

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

看起来不像是Boost问题。此外,您在此处将指针指向堆栈分配的局部变量:

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

这个函数的结束就是我们C++人们所说的未定义的行为,因为ab不再在范围内。

有关详细信息,请参阅此问题。

相关内容

  • 没有找到相关文章

最新更新