Boost Python:将指针设置为null

时间:2017-01-10 21:59:17

标签: 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 = 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的输出如下:

>>> 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 ++)的新手,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

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

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

由于ab不再在范

有关详细信息,请参阅this question