2

I written a wrapper in python for a c++ library and am trying to call it from a flask server so that I can process and display some information however this causes c++ library that is being called through the wrapper to segfault. The library works fine when functions are through the wrapper in main but once calls to the wrapper are embedded in a function they fail.

Calling the same function from main works fine while calling the same function from within another function causes it to fail

I have tried to make sure that the argtypes and restypes I am providing for the function wrapper are correct. Ive tried sending different datatypes / encoding the strings in different ways (and modifying the c++ library accordingly) but this seems to change nothing. I have tried running the flask sever both inside and outside of a virtual environment but this also makes no difference.

Flask code:

from flask import *
import wrapper
from flask_socketio import SocketIO

// If i call wrapper functions from here they work fine
test = wrapper.analysetweets()
print(test)

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on("startanalysis")
def startanalysis():
// If the wrapper functions are called from here they segfault
    test = wrapper.analysetweets()
    print(test);

@app.route("/analysis")
def analysis():
    return render_template("analysis.html")

if __name__ == "__main__":
    socketio.run(app)

Python wrapper code:

from ctypes import *
import json

stdcpp = cdll.LoadLibrary("libstdc++.so.6")
lib = cdll.LoadLibrary('./main.so')

class Tweet(object):
    def __init__(self):
        lib.inittext.argtypes = [c_void_p, c_char_p]
        lib.inittext.restype = None
        self.obj = lib.Tweet_new()

    def inittext(self, st):
        print(self)
        lib.inittext(self.obj, st)

def analysetweets():
    t = Tweet();
    testtext=c_char_p(b'testing'.encode("utf-8"))
    t.inittext(testtext)
    return "Works"

The c++ lib looks something like this:

class Tweet
{
public:
    string text;

    void inittext(char t[280])
    {
        text = t;
    }
}

extern "C"
{
    Tweet *Tweet_new() { return new Tweet(); }
    void inittext(Tweet *tweet, char str[280]) { tweet->inittext(str); }
}

The c++ code is being compiled into a library with the following code:

g++ -c -fPIC -std=c++11 main.cpp -o main.o
g++ -shared -Wl,-soname,main.so -o main.so main.o

The flask server is being run in a virtualenv

Any help would be greatly appreciated :)

Matt
  • 21
  • 3
  • @CristiFati This seemed to fix it thanks! I have a function for deleting pointers too but I thought id omit and code that wasn't strictly relevant. – Matt Sep 05 '19 at 20:48
  • Glad to hear you worked things out!. My previous comment seems ho have autodeleted itself... :) – CristiFati Sep 05 '19 at 23:01

0 Answers0