boost
Utilizzando boost.python
Ricerca…
Esempio introduttivo su Boost.Python
Le cose sono facili quando devi usare una libreria C ++ in un progetto Python. Solo tu puoi usare Boost.
Prima di tutto ecco un elenco di componenti necessari:
- Un file CMakeList.txt, perché stai per utilizzare CMake.
- I file C ++ del progetto C ++.
- Il file python - questo è il tuo progetto python.
Iniziamo con un piccolo file C ++. Il nostro progetto C ++ ha un solo metodo che restituisce una stringa "Questo è il primo tentativo". Chiamalo 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
}
Avere un file CMakeLists.txt un di seguito:
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
Da questa parte del tutorial tutto è così facile. puoi importare la libreria e il metodo call nel tuo progetto python. Chiama il tuo progetto python MyProject.py .
import NativeLib
print (NativeLib.getTryString)
Per eseguire il tuo progetto segui le seguenti istruzioni:
- Crea una directory con il nome build .
- Entra in quella directory.
- Dare il comando
cmake -DCMAKE_BUILD_TYPE=Release .. -
make -
python MyProject.py. Ora, devi vedere la stringa che restituisce il metodo nel tuo progetto C ++.
Wrapping std :: vector in boost.python
Se una funzione restituisce un tipo std::vector , ed è esposto a Python direttamente come
std::vector<float> secondMethod() {
return std::vector<float>();
}
BOOST_PYTHON_MODULE(CppProject) {
boost::python::def("getEmptyVec", secondMethod);
}
poi quando le funzioni vengono chiamate, Python dirà che No to_python (by-value) converter found for C++ type: std::vector<float, std::allocator<float> > , perché Python deve sapere come trattare con std::vector
Fortunatamente boost.python ha fornito una funzione wrapper per noi in vector_indexing_suite.hpp . Il valore restituito può essere gestito come un oggetto FloatVec cui elemento è accessibile dall'operatore [] , esponendo la funzione wrapper corrispondente come segue.
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);
}
Il risultato può essere ulteriormente convertito in un elenco Python o in un array Numpy semplicemente chiamando list() e numpy.asarray() .