【发布时间】: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