So verwende ich Python, um Methoden in einer freigegebenen C++ - Bibliothek aufzurufen. Ich habe ein Problem, das ein Doppel aus dem C++ an den Python zurückgibt. Ich habe ein Spielzeugbeispiel erstellt, das das Problem aufweist. Fühlen Sie sich frei, es zu kompilieren und auszuprobieren. HierGeben Sie C++ zu Python zurück?
ist der Python-Code (soexample.py):
# Python imports
from ctypes import CDLL
import numpy as np
# Open shared CPP library:
cpplib=CDLL('./libsoexample.so')
cppobj = cpplib.CPPClass_py()
# Stuck on converting to short**?
x = cpplib.func_py(cppobj)
print 'x =', x
Hier ist das C++ (soexample.cpp):
#include <iostream>
using namespace std;
class CPPClass
{
public:
CPPClass(){}
void func(double& x)
{
x = 1.0;
}
};
// For use with python:
extern "C" {
CPPClass* CPPClass_py(){ return new CPPClass(); }
double func_py(CPPClass* myClass)
{
double x;
myClass->func(x);
return x;
}
}
Compilieren mit:
g++ -fPIC -Wall -Wextra -shared -o libsoexample.so soexample.cpp
Bei Ich renne ich bekomme:
$ python soexample.py
x = 0
Also das Ergebnis ist eine Ganzzahl vom Typ und von Wert 0. Was ist los?
Ich bin auch neugierig auf das Füllen von Arrays per Referenz.
Das hat super funktioniert! Was meinst du mit 'CPPClass_py.rentyp'? – dillerj
@dillerj es ist eine andere Funktion, die Sie exportieren. Es benötigt auch die Spezifikation des Resttyps. Prüfe POINTER und Struktur. – zch