V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
XIVN1987
V2EX  ›  Python

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

  •  
  •   XIVN1987 · 2021-01-01 00:51:44 +08:00 · 1733 次点击
    这是一个创建于 1183 天前的主题,其中的信息可能已经有所发展或是发生改变。

    按照网上的说明,写了个最简单的 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
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1418 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:46 · PVG 07:46 · LAX 16:46 · JFK 19:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.