【问题标题】:Workaround for PyByteArray_AsString from bytearray that contains null characters来自包含空字符的字节数组的 PyByteArray_AsString 的解决方法
【发布时间】:2021-04-03 21:55:12
【问题描述】:

我有一些数据缓冲区,PyByteArray,我想从中提取 char *。然后我想获取该 char* 并从中创建一个字符串流。

void CKKSwrapper::DeserializeContext(PyObject *obj) {
    // Is a PyByteArray object as determined by https://docs.python.org/3/c-api/bytearray.html#c.PyByteArray_Check
    PyObject_Print(obj, stdout, Py_PRINT_RAW);  // 1
    const char *s = PyByteArray_AsString(obj);  // 2
    std::cout << "Converted bytearray to string" << std::endl;  // 3 
    std::cout << s << std::endl;  // 4


    std::istringstream is(s);  // 5
    lbcrypto::CryptoContext<lbcrypto::DCRTPoly> new_cc; // 6
    Serial::Deserialize(new_cc, is, SerType::BINARY); // 7
}

第二行const char *s = PyByteArray_AsString(obj); 输出一个字符。从上一个问题C++ c_str of std::string returns empty(标题不准确)中,我知道输入对象PyObject *obj 的基础数据中有NULL 字符。

基于API,我没有看到任何直接的解决方案。有人有什么建议吗?

注意:我需要从当前的代码库中去

Server: (C++ -&gt; Python) -&gt; (sockets) -&gt; Client: (Python -&gt; C++)

所以我无法真正绕过 PyObject。

【问题讨论】:

    标签: python c++


    【解决方案1】:

    如果您阅读the description of all the PyByteArray 函数,您会发现一个名为PyByteArray_Size 的有用函数。这为您提供了数组的大小。

    std::string 有很多构造函数。其中一个从开始和结束迭代器构造std::string。指针符合这些条件。所以,你应该能够相应地构造一个完整的std::string

    const char *ptr = PyByteArray_AsString(obj);
    size_t n=PyByteArray_Size(obj);
    
    std::string s{ptr, ptr+n};
    
    std::cout << s << std::endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-06
      • 2016-03-22
      • 1970-01-01
      • 2013-03-17
      • 2018-09-08
      • 2011-12-19
      • 1970-01-01
      • 2012-08-08
      相关资源
      最近更新 更多