boost
Utiliser boost.python
Recherche…
Exemple d'introduction sur Boost.Python
Les choses sont faciles lorsque vous devez utiliser une bibliothèque C ++ dans un projet Python. Juste vous pouvez utiliser Boost.
Tout d'abord, voici une liste des composants dont vous avez besoin:
- Un fichier CMakeList.txt, car vous allez utiliser CMake.
- Les fichiers C ++ du projet C ++.
- Le fichier python - c'est votre projet python.
Commençons par un petit fichier C ++. Notre projet C ++ n'a qu'une seule méthode qui renvoie une chaîne "Ceci est le premier essai". Appelez-le CppProject.cpp
char const *firstMethod() {
return "This is the first try.";
}
BOOST_PYTHON_MODULE(CppProject) {
boost::python::def("getTryString", firstMethod); // boost::python is the namespace
}
Avoir un fichier CMakeLists.txt ci-dessous:
cmake_minimum_required(VERSION 2.8.3)
FIND_PACKAGE(PythonInterp)
FIND_PACKAGE(PythonLibs)
FIND_PACKAGE(Boost COMPONENTS python)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS})
PYTHON_ADD_MODULE(NativeLib CppProject)
FILE(COPY MyProject.py DESTINATION .) # See the whole tutorial to understand this line
Par cette partie du tutoriel, tout est si facile. vous pouvez importer la bibliothèque et la méthode d'appel dans votre projet python. Appelez votre projet python MyProject.py .
import NativeLib
print (NativeLib.getTryString)
Pour exécuter votre projet, suivez les instructions ci-dessous:
- Créez un répertoire avec le nom build .
- Entrez dans ce répertoire.
- Donnez la commande
cmake -DCMAKE_BUILD_TYPE=Release .. -
make -
python MyProject.py. Maintenant, vous devez voir la chaîne que retourne la méthode dans votre projet C ++.
Wrapping std :: vector dans boost.python
Si une fonction retourne un type std::vector , et qu’elle est exposée directement à Python comme
std::vector<float> secondMethod() {
return std::vector<float>();
}
BOOST_PYTHON_MODULE(CppProject) {
boost::python::def("getEmptyVec", secondMethod);
}
ensuite, lorsque les fonctions sont appelées, Python vous indiquera " No to_python (by-value) converter found for C++ type: std::vector<float, std::allocator<float> > , car Python doit savoir comment gérer std::vector .
Heureusement, boost.python a fourni une fonction wrapper pour nous dans vector_indexing_suite.hpp . La valeur FloatVec peut être traitée comme un objet FloatVec dont l'élément peut être accédé par l'opérateur [] , en exposant la fonction wrapper correspondante comme suit.
std::vector<float> secondMethod() {
return std::vector<float>();
}
BOOST_PYTHON_MODULE(CppProject) {
// wrapper function
class_<std::vector<float> >("FloatVec")
.def(vector_indexing_suite<std::vector<float> >());
boost::python::def("getEmptyVec", secondMethod);
}
Le résultat peut être converti en une liste Python ou un tableau Numpy simplement en appelant list() et numpy.asarray() .