ich den Beispielcode in der zweiten Antwort gegeben hier befolgt haben - es Calling C/C++ from python?ctypes - get Ausgabe von C++ Funktion in Python Objekt
und schaffte es ein String-Argument zu nehmen.
Hier ist meine modifizierte CPP-Datei:
#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); }
}
Und dann sieht meine Python-Funktion wie 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')
Dies druckt auf dem Bildschirm "Hallo" und "fd" aber wenn ich mir bei a ist es leer. Wie ändere ich diesen Code, damit das Ergebnis in das Python-Objekt, ein?
EDIT: basierend auf der anderen Frage, die ich an dieser Stelle darauf wurde How to handle C++ return type std::vector<int> in Python ctypes?
versuchte ich folgendes:
from ctypes import *
lib.Foo_bar.restype = c_char_p
a=lib.Foo_bar('fff')
Dies gibt - ein '\ x87 \ x7F'
a = lib.Foo_bar('aaa')
Dies ergibt - ein '\ x87 \ x7f'
Also, gleich, obwohl das Argument anders war nt. Was fehlt mir hier?
'lib.Foo_bar.restype = c_char_p' pro https://docs.python.org/2/library/ctypes.html#return-types –
Mögliche Duplikat [Wie C++ Rückgabetyp std :: vector hand in Python ctypes?] (http://stackoverflow.com/questions/16885344/how-to-handle-c-return-type-stdvectortin-in-python-ctypes) –
Auch für Python3, möchten Sie vielleicht http folgen : //stackoverflow.com/questions/17434977/how-to-customize-python-ctypes-c-wchar-p-and-c-char-p-rrestype –