【环境搭建】pybind11 cmake编译

1,pybind11简介
    pybind11是一个只有头文件的轻量级库,它向Python暴露了C++的类型同时也向C++暴露了Python类型,pybind11主要用于创建现有C++代码的Python绑定。

2,编译
1.1 gcc版本
GCC 4.8或更新版本

sudo apt-get install gcc-4.8 cmake
conda install pytest

1.2 编译pybind11

git clone https://github.com/pybind/pybind11.git
cd pybind11
mkdir build
cd build
cmake ..
cmake --build . --config Release --target check
make check -j 4

3,代码
1,example.cpp

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>

// ----------------
// Regular C++ code
// ----------------

// multiply all entries by 2.0
// input:  nested std::vector ([[...],[...]]) (read-only)
// output: nested std::vector ([[...],[...]]) (new copy)
std::vector<std::vector<double>> modify(const std::vector<std::vector<double>>& input)
{
  std::vector<std::vector<double>> output;

  std::transform(
    input.begin(),
    input.end(),
    std::back_inserter(output),
    [](const std::vector<double> &iv) {
      std::vector<double> dv;
      std::transform(iv.begin(), iv.end(), std::back_inserter(dv), [](double x) -> double { return 2.*x; });
      return dv;
    }
  );

  return output;
}

// ----------------
// Python interface
// ----------------

namespace py = pybind11;

PYBIND11_MODULE(example,m)
{
  m.doc() = "pybind11 example plugin";

  m.def("modify", &modify, "Multiply all entries of a nested list by 2.0");
}

2,CMakeLists.txt

cmake_minimum_required(VERSION 2.8.12)
project(example)

add_subdirectory(pybind11) # 已经编译完的pybind11
pybind11_add_module(example example.cpp)

3,python调用

import example

A = [[1,2,3,4],[5,6]]

B = example.modify(A)

print(B)

4,运行

cmake .
make
python test.py
[[2.0, 4.0, 6.0, 8.0], [10.0, 12.0]]
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在VS Code中配置CMake编译环境,您可以按照以下步骤进行操作: 1. 首先,确保您已经安装了VS Code和CMake。 2. 打开VS Code,点击左侧的扩展图标(或使用快捷键Ctrl+Shift+X)打开扩展面板。 3. 在扩展面板中搜索并安装"CMake Tools"扩展。这个扩展提供了与CMake集成的功能。 4. 安装完成后,点击左侧的调试图标(或使用快捷键Ctrl+Shift+D)打开调试面板。 5. 点击调试面板顶部的齿轮图标,选择"Add Configuration"添加调试配置文件。 6. 在弹出的列表中,选择"C++ (GDB/LLDB)"作为模板。 7. 在生成的launch.json文件中,找到"configurations"数组,并在其中添加以下配置: ```json { "name": "CMake Debug", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build/debug/your_executable_name", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": true, "MIMode": "gdb", "miDebuggerPath": "/path/to/your/gdb" } ``` 请注意替换"your_executable_name"为您的可执行文件的名称,并将"/path/to/your/gdb"替换为您的GDB安装路径(如果使用GDB作为调试器)。 8. 然后,打开您的CMake项目文件夹,并在VS Code的左侧资源管理器中右键单击,选择"CMake: Configure"以生成构建目录。 9. 在资源管理器中再次右键单击,并选择"CMake: Build"以开始构建项目。 10. 最后,点击调试面板顶部的绿色播放按钮即可启动调试会话。 现在,您应该已经成功配置了CMake编译环境,并可以在VS Code中进行调试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值