Handle Python BytesIO, TextIO for LIEF' parsers

Resolve: #49
This commit is contained in:
Romain Thomas
2017-11-01 16:36:35 +01:00
parent 49fdb8dc8f
commit aa70e07791
8 changed files with 217 additions and 5 deletions
+33 -3
View File
@@ -35,9 +35,39 @@ void init_LIEF_Parser_class(py::module& m) {
m.def("parse",
[] (py::object byteio) {
std::cout << "foo" << std::endl;
return nullptr;
[] (py::object byteio, const std::string& name) {
auto&& io = py::module::import("io");
auto&& RawIOBase = io.attr("RawIOBase");
auto&& BufferedIOBase = io.attr("BufferedIOBase");
auto&& TextIOBase = io.attr("TextIOBase");
py::object rawio;
if (py::isinstance(byteio, RawIOBase)) {
rawio = byteio;
}
else if (py::isinstance(byteio, BufferedIOBase)) {
rawio = byteio.attr("raw");
}
else if (py::isinstance(byteio, TextIOBase)) {
rawio = byteio.attr("buffer").attr("raw");
}
else {
throw py::type_error(py::repr(byteio).cast<std::string>().c_str());
}
std::string raw_str = static_cast<py::bytes>(rawio.attr("readall")());
std::vector<uint8_t> raw = {
std::make_move_iterator(std::begin(raw_str)),
std::make_move_iterator(std::end(raw_str))};
return LIEF::Parser::parse(std::move(raw), name);
},
"io"_a,
"name"_a = "",
py::return_value_policy::take_ownership);
}