2017-01-10 1 views
0

파이썬에서 사용할 수 있도록 다음 파일 BoostTest.cpp를 컴파일 중입니다.부스트 파이썬 : 포인터가 null로 설정됩니다.

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

문제는 아주 분명하다 : MYTEST 같이 내가 파이썬 코드에서 길을 잃었 a와 b에 대한 포인터를 MYSTRUCT을 반환하는 경우 다음과 같이

#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); 
} 

파이썬의 출력은(). 이것은 TestFunc()를 실행할 때 발생하지 않으므로 오류가 부스트를 사용하는 방식이어야한다고 생각합니다. Boost (및 C++)에 익숙하지 않으므로 도움을 받으실 수 있습니다.

+0

[로컬 변수의 포인터] (http://stackoverflow.com/questions/4570366/pointer-to-local-variable)의 가능한 복제본 – mascoj

답변

0

부스트 문제인 것처럼 보이지 않습니다. 당신이 포인터가 여기에 지역 변수를 스택 할당을 복용하고있는 moreso 것을 :

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

을이 함수의 끝을지나 것은 우리가 사람들이 ab이 범위에 더 이상 있기 때문에 정의되지 않은 동작을 호출 C++ 것입니다.

자세한 내용은 this question을 참조하십시오.

관련 문제