0

I have a main C++ class Test of which member elements are continuously changed by other C++ classes. These other classes receive a pointer to the Test class in the constructor, which they should keep as a member. It is important that this is a pointer, and that all other classes all change the same Test object. A simplified version looks like this:

test.h

#ifndef TEST_H
#define TEST_H
class Test {
public:
    int a;
    Test();
    Test * get_ptr(void);
    int geta(void);
};
#endif // TEST_H

test.cpp

#include "test.h"
Test::Test() {this->a = 4;};    
Test * Test::get_ptr(void) {return new Test;};    
int Test::geta(void) {return a;};

changer.h

#ifndef CHANGER_H
#define CHANGER_H
#include "test.h"
class Changer {
public:
    Test * t_p;
    Changer(Test * t_ptr);
    void plus1(void);
};    
#endif // CHANGER_H

changer.cpp

#include "changer.h"
Changer::Changer(Test * t_ptr) {t_p = t_ptr;};
void Changer::plus1(void) {t_p->a += 1;};

boost.cpp

#include "test.h"
#include "changer.h"
#include "boost/python.hpp"    
using namespace boost::python;    
BOOST_PYTHON_MODULE(pnt) {
    class_<Test>("Test")
        .def("get_ptr", &Test::get_ptr, return_value_policy<manage_new_object>())
        .def("geta", &Test::geta)
        ;    
    class_<Changer>("Changer", init<Test*>())
        .def("plus1", &Changer::plus1)
        ;
}

This compiles fine, but when I use it in python I get a segmentation fault with this code:

In [1]: import pnt
   ...: t = pnt.Test()
   ...: t.geta()
   ...: c = pnt.Changer(t.get_ptr())
   ...: c.plus1()
   ...: t.geta()
   ...: 
Out[1]: free(): invalid pointer
Aborted (core dumped)

I got the part for the pointer from https://wiki.python.org/moin/boost.python/PointersAndSmartPointers but I can't seem to get it to work. I would greatly appreciate some hints on how to do this.

2
  • The code is confused as to who actually owns the pointer. Both the python wrapper for Test* and Changer think they own the pointer and so both call free, thus causing the seg fault. See this question on who to deal with ownership correctly. stackoverflow.com/questions/4112561/… Commented Apr 9, 2018 at 14:33
  • Possible duplicate of Boost.Python: Ownership of pointer variables Commented Apr 9, 2018 at 14:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.