I am using cython to use python functions in c++, which itself calls a c++ function, Everything compiled perfectly well, but in the end step the error occurs: Segmentation fault (core dumped)
when running the out file, I know its a tough ask to find the mistake but can someone please help me:
#include <iostream>
#include "Python.h"
#include "./plugins/strat_plugin.h" //cython generated header file
int main(int argc, char *argv[])
{
PyRun_SimpleString("import sys\n" "import os");
PyRun_SimpleString("sys.path.append( os.path.dirname(os.getcwd()) +'/plugins/')");
int status=PyImport_AppendInittab("start_plugin", &initstrat_plugin);
if(status==-1){
std::cout<<"error in appendinit"<<"\n";
return -1;//error
}
Py_Initialize();
PyObject *module = PyImport_ImportModule("strat_plugin");
if(module==NULL){
PyErr_Print();
Py_Finalize();
std::cout<<"error in import"<<"\n";
return -1;//error
}
long long ans=0;
std::list<int> a;
ans=gen_fibonacci(a,1,100); //this is the cython function
std::cout<<"ans: "<<ans;
std::cout<<"\n";
}
compile:
g++-8 ./plugins/strat_plugin.c helper.cpp $(python-config --libs) $(python-config --includes) $(python-config --cflags)
strat_plugin.pyx file:
from libcpp.list cimport list
from test import test_sum
cdef public long long gen_fibonacci(list[int] &l,int ind,int n):
num = 3
t1 = 0
t2 = 1
nextTerm = 0
i=1
if ind==1:
l.push_back(0)
l.push_back(1)
i=3
if ind==2:
l.push_back(1)
i=2
while i<n:
nextTerm=t1+t2
t1=t2
t2=nextTerm
if num>=ind:
i=i+1
l.push_back(nextTerm)
num=num+1
return test_sum(l)
This compiles well with the command: cython -2 strat_plugin.pyx
producing header and the c file.
strat.h:
#pragma once
#include <iostream>
#include <list>
long long sum(std::list<int> &);
strategy.cpp
include "strat.h"
using namespace std;
long long sum(list<int> &l)
{
long long s =0;
for(list<int>::const_iterator i = l.begin(); i != l.end(); i++)
s+= *i ;
return s;
}
strat.pyx:
from libcpp.list cimport list
cdef extern from "strat.h":
long long sum(list[int] &)
def test_sum(list[int] l):
return sum(l)
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("test", ["strat.pyx", "strategy.cpp"], language='c++',)]
setup(cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules)
compile using:
python3 setup.py build_ext --inplace
more relevant information: I tried debugging it with gdb and get this:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a2569b in PyImport_GetModuleDict () from /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0
I don't really get the error can someone point out what's wrong?