ipython 中使用 pybind11 生成的 example.pyd 一卡一卡的

2021-01-01 00:51:44 +08:00
 XIVN1987

按照网上的说明,写了个最简单的 pybind11 例程,,操作方法如后面所述,,用的编译器是 tdm64-gcc-9.2.0.exe ,编译生成了 example.pyd ,用 ipython 导入后 ipython 一卡一卡的、光标一直在转圈,,调用 example.add 倒是也能产生正确值,,可是一直很卡,卡到只能关掉 ipython

换了标准的 python.exe 和 jupyter,都没有卡顿的现象

猜测是不是 ipython 对 xxx.pyd 有什么额外要求,,一直在查询 example.pyd 的某个属性,,差不多所以就一卡一卡的??

哪位大神知道原因,,希望指点一下,,谢谢。。

pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code

入门

安装

pip3 install pybind11

编码

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

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

    m.def("add", &add, "A function which adds two numbers");
}

编译

C:\Ubuntu\bin\gcc-win\bin\g++.exe -shared -std=c++11 -DMS_WIN64 -fPIC -Wall -IC:\Python36\include -IC:\Python36\Lib\site-packages\pybind11\include -LC:\Python36\libs example.cc -o example.pyd -lPython36

编译可能报错:

C:/Ubuntu/bin/gcc-win/lib/gcc/x86_64-w64-mingw32/9.2.0/include/c++/cmath:1121:11: error: '::hypot' has not been declared

原因是在 pyconfig.h 中定义 hypot as _hypot,所以解决方法是:在 cmath 文件头部添加

#define _hypot hypot

测试

import example

example.add(2, 3)
5
1757 次点击
所在节点    Python
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/740805

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX