【问题标题】:Boost Python: Pointers being set to nullBoost Python:指针设置为空
【发布时间】:2017-01-10 21:59:17
【问题描述】:

我正在编译以下文件 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++)的新手,因此我们将不胜感激。

【问题讨论】:

标签: python c++ pointers boost null


【解决方案1】:

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

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

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

更多信息请参见this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多