Skip to content

Commit

Permalink
python: Fix conversion with null bytes in bytes object
Browse files Browse the repository at this point in the history
Previously, the returned string was interpreted as a null-terminated
C-string. However, a Python bytes object may contain null bytes in the
string which is why the separately stored string length must be used to
construct the correct string.
  • Loading branch information
taminob committed Feb 19, 2025
1 parent 6146756 commit 1f62971
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/python_object.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,12 @@ std::optional<std::string> PythonObject::asString()
return result;
}
if (PyBytes_Check(object()) != 0) {
auto* result = PyBytes_AsString(object());
const auto* result = PyBytes_AsString(object());
if (result == nullptr) {
return std::nullopt;
}
return std::string { result };
auto length = PyBytes_Size(object());
return std::string { result, 0, static_cast<std::string::size_type>(length) };
}
return std::nullopt;
}
Expand Down

0 comments on commit 1f62971

Please sign in to comment.