0

I'm compiling the following file, BoostTest.cpp, for use in 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);
}

The output from Python is as follows:

>>> 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
>>>

The issue is pretty clear: When I return a MyStruct in the python code, the pointers to a and b are lost as shown by MyTest(). This doesn't occur when running TestFunc(), so I think the error must be in the way I'm using Boost. I'm new to Boost (and c++), so any help would be appreciated.

James H
  • 13
  • 2
  • 5
  • Possible duplicate of [Pointer to local variable](http://stackoverflow.com/questions/4570366/pointer-to-local-variable) – mascoj Jan 10 '17 at 22:10

1 Answers1

0

Doesn't look like it is a Boost issue. Moreso that you are taking the pointer to stack-allocated local variables here:

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

Past the end of this function is what us C++ people call undefined behavior since a and b are no longer in scope.

See this question for more information.

Community
  • 1
  • 1
mascoj
  • 1,313
  • 14
  • 27