Я компилирую следующий файл BoostTest.cpp для использования в Python.Boost 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
>>>
вопрос довольно ясно: Когда я возвращаю MyStruct в коде Python, указатели на а и б теряются, как показано MyTest(). Этого не происходит при запуске TestFunc(), поэтому я думаю, что ошибка должна быть в том, как я использую Boost. Я новичок в Boost (и C++), поэтому любая помощь будет оценена.
Возможный дубликат [Указатель на локальную переменную] (http://stackoverflow.com/questions/4570366/pointer-to-local-variable) – mascoj