Add StructParser utility

This commit is contained in:
Pragyansh Chaturvedi
2025-10-19 22:02:19 +05:30
parent f7874137ad
commit 05d5bba4f7
3 changed files with 59 additions and 3 deletions

View File

@ -10,16 +10,27 @@ include_directories(${CMAKE_SOURCE_DIR}/src)
add_subdirectory(pybind11)
pybind11_add_module(
pylibbpf
# Core
src/core/bpf_program.h
src/core/bpf_exception.h
src/core/bpf_map.h
src/core/bpf_object.h
src/maps/bpf_perf_buffer.h
src/bindings/main.cpp
src/core/bpf_program.cpp
src/core/bpf_map.cpp
src/core/bpf_object.cpp
src/maps/bpf_perf_buffer.cpp)
# Maps
src/maps/bpf_perf_buffer.h
src/maps/bpf_perf_buffer.cpp
# Utils
src/utils/struct_parser.h
src/utils/struct_parser.cpp
# Bindings
src/bindings/main.cpp
)
# --- libbpf build rules ---
set(LIBBPF_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libbpf/src)

View File

@ -0,0 +1,25 @@
#include "struct_parser.h"
#include "core/bpf_exception.h"
StructParser::StructParser(py::dict structs) {
for (auto item : structs) {
std::string name = py::str(item.first);
struct_types_[name] = py::reinterpret_borrow<py::object>(item.second);
}
}
py::object StructParser::parse(const std::string &struct_name, py::bytes data) {
auto it = struct_types_.find(struct_name);
if (it == struct_types_.end()) {
throw BpfException("Unknown struct: " + struct_name);
}
py::object struct_type = it->second;
// Use ctypes.from_buffer_copy() to create struct from bytes
return struct_type.attr("from_buffer_copy")(data);
}
bool StructParser::has_struct(const std::string &struct_name) const {
return struct_types_.find(struct_name) != struct_types_.end();
}

20
src/utils/struct_parser.h Normal file
View File

@ -0,0 +1,20 @@
#ifndef PYLIBBPF_STRUCT_PARSER_H
#define PYLIBBPF_STRUCT_PARSER_H
#include <pybind11/pybind11.h>
#include <string>
#include <unordered_map>
namespace py = pybind11;
class StructParser {
private:
std::unordered_map<std::string, py::object> struct_types_;
public:
explicit StructParser(py::dict structs);
py::object parse(const std::string &struct_name, py::bytes data);
bool has_struct(const std::string &struct_name) const;
};
#endif