Skip to content

Commit a3bbb5c

Browse files
committed
refactor: major modulerization
1 parent 4ea1822 commit a3bbb5c

4 files changed

Lines changed: 290 additions & 239 deletions

File tree

CMakeLists.txt

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,27 @@ project(
1414
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
1515
find_package(pybind11 CONFIG REQUIRED)
1616

17-
# Add a library using FindPython's tooling (pybind11 also provides a helper like
18-
# this)
19-
python_add_library(_core MODULE cpp_src/jsonparser.cpp WITH_SOABI)
17+
# Define source files for the streaming JSON parser
18+
set(PARSER_SOURCES
19+
cpp_src/jsonparser.cpp
20+
)
21+
22+
# Define header files (for IDE integration)
23+
set(PARSER_HEADERS
24+
cpp_src/jsonparser.h
25+
)
26+
27+
# Add a library using FindPython's tooling
28+
python_add_library(_core MODULE
29+
cpp_src/bindings.cpp
30+
${PARSER_SOURCES}
31+
WITH_SOABI
32+
)
33+
34+
# Make sure the include directory is in the include path
35+
target_include_directories(_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/cpp_src)
36+
37+
# Link against pybind11
2038
target_link_libraries(_core PRIVATE pybind11::headers)
2139

2240
# This is passing in the version as a define just as an example

cpp_src/bindings.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
/**
3+
* Python bindings for the streaming JSON parser
4+
*/
5+
6+
#include "jsonparser.h"
7+
#include <pybind11/pybind11.h>
8+
#include <pybind11/stl.h>
9+
10+
namespace py = pybind11;
11+
12+
// macro defined in pybind11.h (common.h)
13+
PYBIND11_MODULE(_core, m) {
14+
m.doc() = "C++ streaming JSON parser with Python bindings";
15+
16+
// Expose the StreamJsonParser class along with its
17+
// constructor and two functions.
18+
// Note that we use getPython for get to return a py::object
19+
py::class_<StreamingJsonParser>(m, "StreamingJsonParser")
20+
.def(py::init<bool>(), py::arg("strict_mode") = false)
21+
.def("consume", &StreamingJsonParser::consume)
22+
.def("get", &StreamingJsonParser::getPython);
23+
24+
// Expose extra function for parsing without explictly creating obj.
25+
m.def("parse_json", [](const std::string& json_str, bool strict_mode = false) {
26+
StreamingJsonParser parser(strict_mode);
27+
parser.consume(json_str);
28+
return parser.getPython();
29+
}, py::arg("json_str"), py::arg("strict_mode") = false);
30+
}

0 commit comments

Comments
 (0)