在C++里初始化并读写pybind11::array_t和pybind11::dict

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值