1

I have been struggling with this for almost a week, maybe someone can help me here? To be short, I wrote a program in C++ and want to link it with Python (to build a web application with Flask or Django).

My C functions which would return an int, char or void work fine, the problem is when they should return a string. I more or less understand what is the cause of the problem (my C function returns a pointer, which my Python function can't handle as a useful data).

So here is an example code that I wrote. In my main.cpp file I have the following the functions:

extern "C" {
  int addint(int a) {
    return a + 1;
  }

  const char* hello() {
    return "hello";
  }
}

and in my pywrapper.py file I have the following:

def addint(number):
    result = lib.addint(c_int(number))
    return result

def saystr():
    result = lib.hello()
    return result

if __name__ == "__main__":
    print('addint: ', addint(5))
    print('saystr: ', saystr())

My output is:

addint:  6
saystr:  -354261249

So the first function works fine. But what can I do for the second function to return 'hello'??

1 Answer 1

1

As the ctypes documentation shows, you need to explicitly tell it how to handle the return type:

def saystr():
    lib.hello.restype = c_char_p # pointer to a string
    result = lib.hello()
    return result

otherwise the default return type is int (and the returned pointer is converted to an integer address).

Sign up to request clarification or add additional context in comments.

Comments

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.