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
Huelse
V2EX  ›  Python

请问 pybind 怎么让函数返回一个比较大的 vector<string>

  •  
  •   Huelse · 2019-05-27 17:23:22 +08:00 · 1956 次点击
    这是一个创建于 1810 天前的主题,其中的信息可能已经有所发展或是发生改变。

    继上一个问题中的回答者的推荐,我采用了 pybind11 来编写 https://www.v2ex.com/t/567858#reply11

    现在的问题是,我无法让函数正确返回这个 vector<string>,里面是 4 个二进制字符串,win 上写入文件大小大约在 33-70kb</string>

    因为直接返回 vector<string>会出现 utf-8 无法识别 0x01 之类的报错,然后用了 py::bytes 这个方法</string>

    我尝试了用引用,这招在 pybing11 的文档里说了不可行,实际也是

    也试过不用 vector<string> 用 py<list>之类的代替,也不行,结果就是 IndexError: list assignment index out of range</list></string>

    如果我采用 py::list 的方式返回,会出现 IndexError: list assignment index out of range

    py::list regist() {
        vector<string> data;
        ...
        py::list list;
        list[0] = py::bytes(data[0]);
        list[1] = py::bytes(data[1]);
        list[2] = py::bytes(data[2]);
        list[3] = py::bytes(data[3]);
        return list;
    }
    PYBIND11_MODULE(seals, m) {
    	m.def("regist", &regist, py::return_value_policy::reference);
    
    }
    

    令人惊讶的是,如果我只返回这四个二进制字符串的一个,是完全没有问题的 例子

    return py::bytes(data[0]);
    

    我有点蒙,请求各位帮助~!

    6 条回复    2019-05-27 23:09:04 +08:00
    ysc3839
        1
    ysc3839  
       2019-05-27 17:57:49 +08:00 via Android   ❤️ 1
    你这里出现 IndexError 大概是因为 list 是空的,list 不是 dict,不会自动帮你分配空间,你大概需要使用 append 之类的来插入。

    https://github.com/pybind/pybind11/blob/97784dad3e518ccb415d5db57ff9b933495d9024/tests/test_pytypes.py#L9-L23
    https://github.com/pybind/pybind11/blob/97784dad3e518ccb415d5db57ff9b933495d9024/tests/test_pytypes.cpp#L14-L21
    Huelse
        2
    Huelse  
    OP
       2019-05-27 22:59:11 +08:00
    @ysc3839 #1 我之前是 append<string>导致问题,现在啊 hi 姐 append()是没问题的,实在被自己蠢到了,感谢您~
    Huelse
        3
    Huelse  
    OP
       2019-05-27 23:03:56 +08:00
    @ysc3839 #1 我现在在做怎么移植到 linux 上了
    ysc3839
        4
    ysc3839  
       2019-05-27 23:04:15 +08:00   ❤️ 1
    不能用 string 大概是因为 Python 会 decode 成 Unicode 字符串,只能用 bytes。
    Huelse
        5
    Huelse  
    OP
       2019-05-27 23:08:00 +08:00
    @ysc3839 #4 嗯嗯,我直接全部 py::bytes 返回了
    ysc3839
        6
    ysc3839  
       2019-05-27 23:09:04 +08:00
    @Huelse 按照 pybind11 文档来写 CMakeLists.txt ,同时代码没有涉及系统 API 的话应该可以直接在 Linux 下编译通过。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1191 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 23:05 · PVG 07:05 · LAX 16:05 · JFK 19:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.