Skip to content

Commit 6c82c6d

Browse files
authored
Merge pull request #2 from fiskrt/modulerize
refactor: major modulerization
2 parents 4ea1822 + f364b36 commit 6c82c6d

4 files changed

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

0 commit comments

Comments
 (0)