2017-01-10 1 views
0

私は次のBoostTest.cppファイルをPythonで使用するためにコンパイルしています。Boost Python:ポインタがnullに設定されています

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

次のようにパイソンからの出力は次のようになります。

>>> 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を返すときのMyTestによって示されるように、aとbへのポインタが失われます()。これはTestFunc()を実行しているときには発生しないので、エラーはBoostを使用している方法でなければならないと思います。私は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を参照してください。

関連する問題