2

I've followed the sample code in the second answer given here - Calling C/C++ from python?

and managed to get it to take a string argument.

Here is my modified cpp file:

#include <iostream>

using namespace std;

class Foo{
    public:
        char* bar(char in[1000]){
            std::cout << "Hello" << std::endl;
            std::cout << in << std::endl;
            return in;
        }
};

extern "C" {
    Foo* Foo_new(){ return new Foo(); }
    char* Foo_bar(Foo* foo, char in[1000]){ return foo->bar(in); }
}

And then my python function looks like so -

from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')

class Foo(object):
    def __init__(self):
        self.obj = lib.Foo_new()

    def bar(self, st):
        lib.Foo_bar(self.obj, st)

f = Foo()
a = f.bar('fd')

This prints to the screen "Hello" and "fd" but when I look at a, it is empty. How do I modify this code so that the result can be fed into the python object, a?

EDIT: based on the other question I was pointed to here, How to handle C++ return type std::vector<int> in Python ctypes?

I tried the following:

from ctypes import *
lib.Foo_bar.restype = c_char_p
a=lib.Foo_bar('fff')

This gives - a '\x87\x7f'

a = lib.Foo_bar('aaa')

This gives - a '\x87\x7f'

So, same even though argument was different. What am I missing here?

5

1 Answer 1

1

@Paul Mu Guire's suggestion above might have helped, but what I needed was something really simple that took a string and output a string. So, the whole object oriented paradigm was overkill. I changed to a simple C structure -

extern "C" {
char* linked(char * in){ 
    return in;
  }
}

and it worked quite well after doing the lib.linked.restype = c_char_p.

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.