수색…


Boost.Python에 대한 소개 사례

상황은 Python 프로젝트에서 C ++ 라이브러리를 사용해야 할 때 쉽습니다. Boost를 사용할 수 있습니다.

우선 여기에 필요한 구성 요소 목록이 있습니다.

  • CMake를 사용하기 때문에 CMakeList.txt 파일.
  • C ++ 프로젝트의 C ++ 파일.
  • 파이썬 파일 - 이것은 파이썬 프로젝트입니다.

작은 C ++ 파일부터 시작해 보겠습니다. 우리의 C ++ 프로젝트에는 "이것은 첫 번째 시도입니다."라는 문자열을 반환하는 메서드가 하나뿐입니다. 그것을 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
}

CMakeLists.txt 파일을 다음과 같이 작성하십시오.

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

튜토리얼의이 부분에서 모든 것이 매우 쉽습니다. 파이썬 프로젝트에서 라이브러리와 메소드를 가져올 수 있습니다. Python 프로젝트 MyProject.py를 호출하십시오.

import NativeLib
print (NativeLib.getTryString)

프로젝트를 실행하려면 아래 지침을 따르십시오.

  • build 라는 이름의 디렉토리를 만듭니다.
  • 해당 디렉토리에 입력하십시오.
  • cmake -DCMAKE_BUILD_TYPE=Release .. 명령을 내 cmake -DCMAKE_BUILD_TYPE=Release ..
  • make
  • python MyProject.py . 이제 C ++ 프로젝트의 메서드에서 반환하는 문자열을 확인해야합니다.

boost.python에서 std :: vector 래핑하기

함수가 std::vector 형식을 반환하고 Python에 직접 노출되면

std::vector<float> secondMethod() {
    return std::vector<float>();
}

BOOST_PYTHON_MODULE(CppProject) {
    boost::python::def("getEmptyVec", secondMethod);
}

함수가 호출 될 때 파이썬은 No to_python (by-value) converter found for C++ type: std::vector<float, std::allocator<float> > 를 말할 것입니다 No to_python (by-value) converter found for C++ type: std::vector<float, std::allocator<float> > 왜냐하면 파이썬은 std::vector 를 다루는 방법을 알아야하기 때문입니다 std::vector .

다행스럽게도 boost.python은 vector_indexing_suite.hpp 에서 우리를위한 래퍼 vector_indexing_suite.hpp . 반환 값은 다음과 같이 해당 래퍼 함수를 ​​노출하여 [] 연산자로 요소에 액세스 할 수있는 FloatVec 객체로 처리 할 수 ​​있습니다.

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);
}

결과는 list()numpy.asarray() 를 호출하여 Python 목록이나 Numpy 배열로 더 변환 할 수 있습니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow