I'm using python with swig.
The cpp file contains a variable int step=0;
and a function use the variable void test();
I get a segmentation fault when I call the function in python.
But after I change the variable name to step2, it works.
Version: swig 4.0.0 python 3.6.7
This get a segmentation fault:
1.ex.cpp
#include<iostream>
int step = 0;
void test(){
step += 1;
printf("ok\n");
}
2.ex.i
%module ex
%inline %{
extern void test();
%}
3.run
swig -c++ -python ex.i
g++ -fPIC -c ex.cpp -c ex_wrap.cxx -I/home/lzhang/venv/include/python3.6m
g++ -shared ex.o ex_wrap.o -o _ex.so
4.get a segmentation fault
$ python
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex
>>> ex.test()
Segmentation fault (core dumped)
But I only change variable name:
#include<iostream>
int step2 = 0;
void test(){
step2 += 1;
printf("ok\n");
}
After recompile, it works.
$ python
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex
>>> ex.test()
ok
>>>
How can I avoid this kind of error?