windows 10 上使用pybind11进行C++和Python代码相互调用 | Interfacing C++ and Python with pybind11 on windows 10
本文首发于个人博客https://kezunlin.me/post/8b9c051d/,欢迎阅读!
Interfacing C++ and Python with pybind11 on windows 10
Series
- Part 1: Interfacing C++ and Python with pybind11 on windows 10
- Part 2: Interfacing C++ and Python with pybind11 on ubuntu 16.04
Guide
requirements:
- pybind11 v2.3.dev0
- python 2.7
install pytest
pip install pytest
compile
git clone https://github.com/pybind/pybind11.git
cd pybind11
mkdir build
cd build
cmake-gui ..
with options
PYBIND11_CPP_STANDARD /std:c++11 # default c++14
PYTHON_EXECUTABLE C:/Python27/python.exe
CMAKE_INSTALL_PREFIX C:/Program Files/pybind11
compile with VS 2015 with x64 Release
install to C:\Program Files\pybind11 with only include and share
$ tree .
.
├── include
│ └── pybind11
│ ├── attr.h
│ ├── buffer_info.h
│ ├── cast.h
│ ├── chrono.h
│ ├── common.h
│ ├── complex.h
│ ├── detail
│ │ ├── class.h
│ │ ├── common.h
│ │ ├── descr.h
│ │ ├── init.h
│ │ ├── internals.h
│ │ └── typeid.h
│ ├── eigen.h
│ ├── embed.h
│ ├── eval.h
│ ├── functional.h
│ ├── iostream.h
│ ├── numpy.h
│ ├── operators.h
│ ├── options.h
│ ├── pybind11.h
│ ├── pytypes.h
│ ├── stl.h
│ └── stl_bind.h
└── share
└── cmake
└── pybind11
├── FindPythonLibsNew.cmake
├── pybind11Config.cmake
├── pybind11ConfigVersion.cmake
├── pybind11Targets.cmake
└── pybind11Tools.cmake
6 directories, 29 files
Usage
pybind11 (cpp--->python)
module: examplelib
target: examplelib
cpp: example.cpp
example.cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
/*
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
struct Pet {
Pet(const std::string &name) : name(name) { }
void setName(const std::string &name_) { name = name_; }
const std::string &getName() const { return name; }
std::string name;
};
/*
module: examplelib
target: examplelib
cpp: example.cpp
*/
PYBIND11_MODULE(examplelib, m)
{
// optional module docstring
m.doc() = "pybind11 example plugin";
// FUNCTIONS
// expose add function, and add keyword arguments and default arguments
m.def("add", &add, "A function which adds two numbers", py::arg("i") = 1, py::arg("j") = 2);
// DATA
// exporting variables
m.attr("the_answer") = 42;
py::object world = py::cast("World");
m.attr("what") = world;
// CLASSES
py::class_<Pet>(m, "Pet")
.def(py::init<const std::string &>())
.def("setName", &Pet::setName)
.def("getName", &Pet::getName);
/*
python3
> help(examplelib)
*/
}
CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (pybind)
enable_language(C)
enable_language(CXX)
find_package(pybind11 CONFIG REQUIRED)
include_directories(${pybind11_INCLUDE_DIRS})
message([MAIN] "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}")
MESSAGE( [Main] " pybind11_INCLUDE_DIRS = ${pybind11_INCLUDE_DIRS}")
MESSAGE( [Main] " pybind11_LIBRARIES = ${pybind11_LIBRARIES}")
#
# # Create an extension module
# add_library(mylib MODULE main.cpp)
# target_link_libraries(mylib pybind11::module)
#
# # Or embed the Python interpreter into an executable
# add_executable(myexe main.cpp)
# target_link_libraries(myexe pybind11::embed)
# method (1): generate `examplelib.pyd`
pybind11_add_module(examplelib example.cpp)
# method (2): generate `examplelib.dll` rename to `examplelib.pyd`
#add_library(examplelib MODULE example.cpp)
#target_link_libraries(examplelib pybind11::module)
MESSAGE( [Main] " pybind11_INCLUDE_DIRS = ${pybind11_INCLUDE_DIRS}")
MESSAGE( [Main] " pybind11_LIBRARIES = ${pybind11_LIBRARIES}")
#add_executable(cpp_use_python cpp_use_python.cpp)
#target_link_libraries(cpp_use_python PRIVATE pybind11::embed)
cmake and config

build with vs and we get 3 files:
examplelib.lib
examplelib.exp
examplelib.cp35-win_amd64.pyd
python import examplelib
python3
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import examplelib
>>> help(examplelib)
Help on module examplelib:
NAME
examplelib - pybind11 example plugin
CLASSES
pybind11_builtins.pybind11_object(builtins.object)
Pet
class Pet(pybind11_builtins.pybind11_object)
| Method resolution order:
| Pet
| pybind11_builtins.pybind11_object
| builtins.object
|
| Methods defined here:
|
| __init__(...)
| __init__(self: examplelib.Pet, arg0: str) -> None
|
| getName(...)
| getName(self: examplelib.Pet) -> str
|
| setName(...)
| setName(self: examplelib.Pet, arg0: str) -> None
|
| ----------------------------------------------------------------------
| Methods inherited from pybind11_builtins.pybind11_object:
|
| __new__(*args, **kwargs) from pybind11_builtins.pybind11_type
| Create and return a new object. See help(type) for accurate signature.
FUNCTIONS
add(...) method of builtins.PyCapsule instance
add(i: int = 1, j: int = 2) -> int
A function which adds two numbers
DATA
the_answer = 42
what = 'World'
FILE
e:\git\car\extra\pybind11\build\release\examplelib.cp35-win_amd64.pyd
>>> p = examplelib.Pet('kzl')
>>> print(p)
<examplelib.Pet object at 0x0000025EED9E3D18>
>>> p.getName()
'kzl'
>>> examplelib.add(1,2)
3
>>> examplelib.the_answer
42
>>> examplelib.what
'World'
>>>
embed
example.py
def add(i, j):
print("hello, pybind11")
return i+j
class MyMath:
def __init__(self,name):
self.name = name
def my_add(self,i,j):
return i + j
def my_strcon(self,a,b):
return a + b
cpp_use_python.cpp
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
int main() {
py::scoped_interpreter python;
/*
import sys
print sys.path
print "Hello,World!"
*/
py::module sys = py::module::import("sys");
py::print(sys.attr("path"));
py::print("Hello, World!"); // use the Python API
/*
import example
n = example.add(1,2)
*/
py::module example = py::module::import("example");
py::object result = example.attr("add")(1, 2);
int n = result.cast<int>();
assert(n == 3);
std::cout << "result from example.add(1,2) = " << n << std::endl;
/*
from example import MyMath
obj = MyMath("v0")
obj.my_add(1,2)
*/
py::object MyMath = py::module::import("example").attr("MyMath"); // class
py::object obj = MyMath("v0"); // class object
py::object my_add = obj.attr("my_add");// object method
py::object result2 = my_add(1, 2); // result
int n2 = result2.cast<int>(); // cast from python type to c++ type
assert(n2 == 3);
std::cout << "result from obj.my_add(1,2) = " << n2 << std::endl;
/*
from example import MyMath
obj = MyMath("v0")
obj.my_strcon("abc","123");
*/
py::object my_strcon = obj.attr("my_strcon"); // object method
py::object result3 = my_strcon("abc", "123");
std::string str3 = result3.cast<std::string>();
std::cout << "result from obj.my_strcon(abc,123) = " << str3 << std::endl;
return 0;
}
CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (pybind)
enable_language(C)
enable_language(CXX)
find_package(pybind11 CONFIG REQUIRED)
include_directories(${pybind11_INCLUDE_DIRS})
MESSAGE( [Main] " pybind11_INCLUDE_DIRS = ${pybind11_INCLUDE_DIRS}")
MESSAGE( [Main] " pybind11_LIBRARIES = ${pybind11_LIBRARIES}")
add_executable(cpp_use_python cpp_use_python.cpp)
target_link_libraries(cpp_use_python PRIVATE pybind11::embed)
Reference
History
- 20180301: created.
Copyright
- Post author: kezunlin
- Post link: https://kezunlin.me/post/8b9c051d/
- Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.
windows 10 上使用pybind11进行C++和Python代码相互调用 | Interfacing C++ and Python with pybind11 on windows 10的更多相关文章
- ubuntu 16.04 上使用pybind11进行C++和Python代码相互调用 | Interfacing C++ and Python with pybind11 on ubuntu 16.04
本文首发于个人博客https://kezunlin.me/post/a41adc1/,欢迎阅读! Interfacing C++ and Python with pybind11 on ubuntu ...
- Windows平台上通过git下载github的开源代码
常见指令整理: (1)检查ssh密钥是否已经存在.GitBash. 查看是否已经有了ssh密钥:cd ~/.ssh.示例中说明已经存在密钥 (2)生成公钥和私钥 $ ssh-keygen -t rsa ...
- Windows 10上源码编译Poco并编写httpserver和tcpserver | compile and install poco cpp library on windows
本文首发于个人博客https://kezunlin.me/post/9587bb47/,欢迎阅读! compile and install poco cpp library on windows Se ...
- service层代码相互调用, 导致spring循环依赖,设计上的优化
管理员创建用户需要发送激活邮件, 而发送激活邮件的时候需要判断发件人是不是合法的用户, 因此设计到一个循环依赖的问题 //UserService @Service class UserService{ ...
- DB 查询分析器 6.04 在 Windows 10 上的安装与运行展示
DB查询分析器 6.04 在 Windows 10 上的安装与运行展示 中国本土程序员马根峰(CSDN专访马根峰:海量数据处理与分析大师的中国本土程序员 http://www.csdn.net/art ...
- (转)在Windows平台上安装Node.js及NPM模块管理
本文转载自:http://www.cnblogs.com/seanlv/archive/2011/11/22/2258716.html 之前9月份的时候我写了一篇关于如何在Windows平台上手工管理 ...
- Windows 10 上强制Visual Studio以管理员身份运行
Windows 10 的一个既安全又蛋疼之处是UAC的行为被改变了.以往在Windows 7中,只要关闭了UAC,自己的帐号又是本机管理员组的,任何程序都会以管理员身份启动.然而,在Windows 8 ...
- 在Windows 10上安装Oracle 11g数据库出现的问题及解决
在Windows 10上安装Oracle 11g数据库,并且很多次出现过:当安装的进度条进行到快要结束的时候弹出一个提示框.如下: [Java(TM)2 Platform Standard Editi ...
- Windows 10 上,Edge 浏览器不支持插件,因此将不运行 Java
在 Windows 10 上,Edge 浏览器不支持插件,因此将不运行 Java.微软想干嘛?
随机推荐
- Unity - HasExitTime用法
本文详细分析了AnimatorController中动画切换过渡问题,即Translation过渡及hasExitTime的问题.方法为对实际项目中的所有情况进行分类,规划逻辑图,可视化分析解决这些问 ...
- 浅谈原理--hashCode方法
我们时常会判断一个元素是否相等重复,可以用equals方法. 每增加一个元素,我们就可以通过equals方法判断集合中的每一个元素是否重复,但是如果集合中有10000个元素了,我们每添加一个元素的时候 ...
- .NET Framework概述
1.NET Framework是为其运行的应用程序提供各种服务的托管执行环境,它包括两个主要组件:(1).公共语言运行时 (CLR),(2)..NET Framework 类库: 2.NET Fram ...
- React-Native转小程序调研报告:Taro & Alita
一. 我们的要求 期望的要求 基于React语法,将RN项目转化为小程序项目 该小程序能同时在 微信小程序 和 支付宝小程序这两个平台运行 底线要求 底线是能转成微信小程序,因为目前来说,因为微信先发 ...
- ThreadPoolExecutor源码中的适配器模式
什么是适配器模式 网上已有很多的教程,不细讲了.可以参考:五分钟了解设计模式(3)---适配器模式 在适配器模式中,一定要识别清楚,Target Adaptee Adapter分别是哪些类或接口,这样 ...
- .NET进阶篇05-Linq、Lambda表达式
知识需要不断积累.总结和沉淀,思考和写作是成长的催化剂 内容目录 一.Lambda表达式1.匿名方法2.Lambda表达式二.Linq概述三.查询操作符1.linq初见2.常用查询操作符筛选排序分组连 ...
- 让你的sql开启氮气加速
事情的过程是:公司有一个上百行的sql 运行在MySQL数据库,速度奇慢无比,逻辑乱七八糟,我就不贴出来了,经过这次修改想总结一下如何写一个不被人骂的sql. 说一些被人诟病的问题: 一.子查询 把你 ...
- 开源.Net Standard版华为物联网北向接口SDK
最近用到了华为的物联网平台API,但是官方没有.Net版的SDK,所以就自己封装了一个,开源出来给有需要的朋友,同时也算是为.Net Core的发展做点小贡献~ 源码地址:https://github ...
- java中Arrays.sort()对二位数组进行排序
int [][]a = new int [5][2]; //定义一个二维数组,其中所包含的一维数组具有两个元素 对于一个已定义的二位数组a经行如下规则排序,首先按照每一个对应的一维数组第一个元素进行升 ...
- 【MySQL】MySQL数据类型
MySQL表数据存储大小说明 MySQL中规定,任何一条记录(数据表中每行数据)理论上的最大存储容量为 2^16 - 1 (Bytes) = 65535字节. MySQL数据类型思维导图 MySQL数 ...