簡體   English   中英

使用 pybind11 在 C++ 和 C++ 之間傳遞 Python 大整數(>256 位)

[英]Passing Python large integers (>256bits) to and from C++ with pybind11

我正在為基於 C++ 的加密方案開發一個 python 包裝器,其中密鑰和密文是非常大的數字(最多 2048 位)。

在 C++ 中,我使用Intel BigNumber 類來存儲和處理如此大的數字。

由於 Python 本身支持通過對象“看似”無限位的整數,因此我無法通過 Python 將此類變量作為參數傳遞。

  py::class_<BigNumber>(m, "BigNumber")
      .def(py::init<unsigned int>())
      .def(py::init<int>())
      .def(py::init<BigNumber>())
      .def(py::init([](py::list data) {
        size_t length = data.size();
        unsigned int* pData = new unsigned int[length];
        for (int i = 0; i < length; i++) {
          pData[i] = data[i].cast<unsigned int>();
        }
        return std::unique_ptr<BigNumber>(new BigNumber(pData, length));
      }))
      .def(py::init([](py::array_t<unsigned int> data) {
        py::buffer_info buffer_info = data.request();

        unsigned int* pData = static_cast<unsigned int*>(buffer_info.ptr);
        std::vector<ssize_t> shape = buffer_info.shape;
        return std::unique_ptr<BigNumber>(new BigNumber(pData, shape[0]));
      }))

以上部分允許最多 32 位單個變量或分解大整數的列表/數組(每個 32 位)

如果我想從 Python 中獲取非常大的整數作為輸入來填充BigNumber類,我應該怎么做才能定義一個def_property_readonly()函數,該函數作為 Python 可理解的大整數對象返回?

編輯 1:將大整數從 Python 傳遞到 C++ 在BigNumber(const char* s)構造BigNumber(const char* s)的幫助下,可以通過以下方式完成:

      .def(py::init([](py::object obj){
        std::string s_obj = py::str(obj);
        return std::unique_ptr<BigNumber>(new BigNumber(&s_obj[0]));
      }))

弄清楚如何使用py::cast進行反向操作,可能是std::stringpy::object

第一種情況的答案:使用 BigNumber 將非常大的整數(> 256 位)對象從 Python 傳遞到 C++

將大整數從 Python 傳遞到 C++ 在BigNumber(const char* s)構造BigNumber(const char* s)的幫助下,可以通過以下方式完成:

.def(py::init([](py::object obj){
  std::string s_obj = py::str(obj);
  return std::make_unique<BigNumber>(s_obj.c_str());
}))

然而,用大整數對象返回 Python 仍然是 WIP

我嘗試使用py::int_返回 python:

.def("val", [](BigNumber const& self){
  std::string s_hex;
  self.num2hex(s_hex);
  return py::int_(s_hex);
})

但是,當您嘗試時,這會調用相同的值錯誤

>>> int("0x12345")

在 Python 中。

ValueError: invalid literal for int() with base 10: '0x12345'

暫無
暫無

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

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