Skip to content

Commit 05d5bba

Browse files
committed
Add StructParser utility
1 parent f787413 commit 05d5bba

File tree

3 files changed

+59
-3
lines changed

3 files changed

+59
-3
lines changed

CMakeLists.txt

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,27 @@ include_directories(${CMAKE_SOURCE_DIR}/src)
1010
add_subdirectory(pybind11)
1111
pybind11_add_module(
1212
pylibbpf
13+
14+
# Core
1315
src/core/bpf_program.h
1416
src/core/bpf_exception.h
1517
src/core/bpf_map.h
1618
src/core/bpf_object.h
17-
src/maps/bpf_perf_buffer.h
18-
src/bindings/main.cpp
1919
src/core/bpf_program.cpp
2020
src/core/bpf_map.cpp
2121
src/core/bpf_object.cpp
22-
src/maps/bpf_perf_buffer.cpp)
22+
23+
# Maps
24+
src/maps/bpf_perf_buffer.h
25+
src/maps/bpf_perf_buffer.cpp
26+
27+
# Utils
28+
src/utils/struct_parser.h
29+
src/utils/struct_parser.cpp
30+
31+
# Bindings
32+
src/bindings/main.cpp
33+
)
2334

2435
# --- libbpf build rules ---
2536
set(LIBBPF_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libbpf/src)

src/utils/struct_parser.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include "struct_parser.h"
2+
#include "core/bpf_exception.h"
3+
4+
StructParser::StructParser(py::dict structs) {
5+
for (auto item : structs) {
6+
std::string name = py::str(item.first);
7+
struct_types_[name] = py::reinterpret_borrow<py::object>(item.second);
8+
}
9+
}
10+
11+
py::object StructParser::parse(const std::string &struct_name, py::bytes data) {
12+
auto it = struct_types_.find(struct_name);
13+
if (it == struct_types_.end()) {
14+
throw BpfException("Unknown struct: " + struct_name);
15+
}
16+
17+
py::object struct_type = it->second;
18+
19+
// Use ctypes.from_buffer_copy() to create struct from bytes
20+
return struct_type.attr("from_buffer_copy")(data);
21+
}
22+
23+
bool StructParser::has_struct(const std::string &struct_name) const {
24+
return struct_types_.find(struct_name) != struct_types_.end();
25+
}

src/utils/struct_parser.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#ifndef PYLIBBPF_STRUCT_PARSER_H
2+
#define PYLIBBPF_STRUCT_PARSER_H
3+
4+
#include <pybind11/pybind11.h>
5+
#include <string>
6+
#include <unordered_map>
7+
8+
namespace py = pybind11;
9+
10+
class StructParser {
11+
private:
12+
std::unordered_map<std::string, py::object> struct_types_;
13+
14+
public:
15+
explicit StructParser(py::dict structs);
16+
py::object parse(const std::string &struct_name, py::bytes data);
17+
bool has_struct(const std::string &struct_name) const;
18+
};
19+
20+
#endif

0 commit comments

Comments
 (0)