cmake
cmake_minimum_required(VERSION 3.5.1)
set( CMAKE_CXX_FLAGS "-std=c++11" )
set(CMAKE_BUILD_TYPE "Release")
project(demo)
set(pybind11_DIR /usr/local/share/cmake/pybind11)
find_package(pybind11 REQUIRED)
include_directories(
"/usr/include/python3.6m"
)
file(GLOB SRC src/*.cpp src/*.h)
add_executable(demo ${SRC})
target_link_libraries(demo ${pybind11} -lpython3.6m)
以下档案都放在src目录下
main.cpp
#include "examples.h"
#include <iostream>
int main() {
array_t_demo();
dict_demo();
std::cout<<"done"<<std::endl;
return 0;
}
examples.h
#ifndef DEMO_EXAMPLES_H
#define DEMO_EXAMPLES_H
void array_t_demo();
void dict_demo();
#endif //DEMO_EXAMPLES_H
array_t_demo.cpp
//
// Created by hao on 2022/6/5.
//
#include "examples.h"
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <iostream>
#include <pybind11/embed.h>
namespace py = pybind11;
void prt_array(const py::array_t<double>& arr){
py::buffer_info buf = arr.request();
auto *ptr = static_cast<double *>(buf.ptr);
std::cout<<ptr[0]<<std::endl;
std::cout<<ptr[1]<<std::endl;
std::cout<<ptr[2]<<std::endl;
std::cout<<arr.size()<<std::endl;
}
void array_t_demo() {
py::scoped_interpreter guard{};
auto result = py::array_t<double>(3);//申请空间
py::buffer_info buf = result.request();
auto *ptr = static_cast<double *>(buf.ptr);
ptr[0]=16.5;
ptr[1]=0.9;
ptr[2]=-0.09;
prt_array(result);
}
dict_demo.cpp
//
// Created by hao on 2022/6/4.
//
#include "examples.h"
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
#include <pybind11/stl.h>
#include <iostream>
namespace py = pybind11;
void dict_demo() {
py::scoped_interpreter guard{}; // <= Initialize the interpreter
py::dict dict;
dict["a"] = 1; // throws exception error - ptyes.h Line 546
dict["b"] = 2; // throws exception error - ptyes.h Line 546
for (auto item : dict)
{
std::cout << "key: " << item.first << ", value=" << item.second << std::endl;
};
int size = dict.size();
std::cout << size << std::endl;
}
运行结果
16.5
0.9
-0.09
3
key: a, value=1
key: b, value=2
2
done
Process finished with exit code 0