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?

Community
  • 1
  • 1
Rohit Pandey
  • 2,443
  • 7
  • 31
  • 54
  • `lib.Foo_bar.restype = c_char_p` per https://docs.python.org/2/library/ctypes.html#return-types – Dima Tisnek Jul 03 '16 at 08:47
  • Possible duplicate of [How to handle C++ return type std::vector in Python ctypes?](http://stackoverflow.com/questions/16885344/how-to-handle-c-return-type-stdvectorint-in-python-ctypes) – Dima Tisnek Jul 03 '16 at 08:49
  • Also, for Python3, you may want to follow http://stackoverflow.com/questions/17434977/how-to-customize-python-ctypes-c-wchar-p-and-c-char-p-restype – Dima Tisnek Jul 03 '16 at 08:49
  • Shoutd that be `return lib.Foo_bar(self.obj, st)`? – PaulMcG Jul 03 '16 at 09:45
  • 1
    You may also need these:`lib.Foo_new.restype = c_void_p; lib.Foo_bar.argtypes = [c_void_p, c_char_p]` – PaulMcG Jul 03 '16 at 09:56

1 Answers1

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.

Rohit Pandey
  • 2,443
  • 7
  • 31
  • 54