Skip to content
Advertisement

Segmentation fault when importing a C++ shared object in Python

I have the following shared object:

MyLib.cpp

JavaScript

That I compile with: g++ -fPIC -shared -o MyLib.so MyLib.cpp

I then use it with the following Python script:

script.py

JavaScript

Like this, it works perfectly, but if I uncomment the line //var = 10;, Python makes a segmentation fault (Python 3.8). This happens every time the object MyClass makes a change to one of its local variable (except inside the constructor, where it works). It looks like the address of the variable var is wrong and when accessing it, there is a segmentation fault. I tried using the keyword “virtual” for function without any change, and I tried to import the shared object in another C++ program using dlfcn, which worked fine. Any idea what is wrong ?

Advertisement

Answer

The pointers are not the same:

JavaScript

Running I get:

JavaScript

Looks like somewhere there was a sign extension issue.

You need to tell the python the type of the objects being passed around otherwise it thinks they are int and nasty things happen:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement