簡體   English   中英

Pybind11:將元組列表從 Python 傳遞到 C++

[英]Pybind11: Passing list of tuples from Python to C++

我正在使用 pybind11,我想將元組(坐標)列表從 Python 傳遞到 C++。 這是示例 C++ 代碼:

parse_coords(py::list coords) {
    std::vector<PointI> coordinates(py::len(coords));
    
    for (size_t i = 1; i < py::len(coords); i++) {
        coordinates[i].x = coords[i][0];
        coordinates[i].z = coords[i][1];
    }
}

顯然,這是行不通的。 我得到的錯誤是cannot convert 'pybind11::detail::item_accessor' {aka 'pybind11::detail::accessor<pybind11::detail::accessor_policies::generic_item>'} to 'int' in assignment

如何傳遞比 int 更復雜的列表,這是我能找到的所有示例?

你必須使用py::cast 如果沒有為您的自定義類型注冊的轉換 function,或者類型不匹配,那么您將得到一個異常:

例子:

void cast_test(const py::list& l)
{
    for(auto it = l.begin(); it != l.end(); ++it)
    {
        std::cout << it->cast<int>() << std::endl;
    }
}
>>> example.cast_test([1,2,3])
1
2
3
>>> example.cast_test([1,2,"a"])
1
2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Unable to cast Python instance to C++ type (compile in debug mode for details)
>>> 

在這里您可以找到有關內置演員表的更多詳細信息: https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object.html

在這里如何添加自定義類型腳輪: https://pybind11.readthedocs.io/en/stable/advanced/cast/custom.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM