3
3
#include < iostream>
4
4
#include < cstring>
5
5
6
- extern " C " bool embit_miniscript_miniscript_parse (const char * input) {
6
+ static bool call_python_parser (const char * input, const char * function_name ) {
7
7
if (!Py_IsInitialized ()) {
8
8
Py_Initialize ();
9
-
10
9
PyRun_SimpleString (" import sys; sys.path.append('.')" );
11
10
}
12
11
@@ -15,20 +14,20 @@ extern "C" bool embit_miniscript_miniscript_parse(const char* input) {
15
14
16
15
bool success = false ;
17
16
PyObject* main_module = NULL ;
18
- PyObject* miniscript_parse_func = NULL ;
17
+ PyObject* parse_func = NULL ;
19
18
PyObject* args = NULL ;
20
19
PyObject* result = NULL ;
21
20
PyObject* input_str = NULL ;
22
21
23
- // Import the main Python module containing miniscript_parse
22
+ // Import the main Python module containing the parser function
24
23
main_module = PyImport_ImportModule (" main" );
25
24
if (!main_module) {
26
25
goto cleanup;
27
26
}
28
27
29
- // Get the miniscript_parse function from the module
30
- miniscript_parse_func = PyObject_GetAttrString (main_module, " miniscript_parse " );
31
- if (!miniscript_parse_func || !PyCallable_Check (miniscript_parse_func )) {
28
+ // Get the parser function from the module
29
+ parse_func = PyObject_GetAttrString (main_module, function_name );
30
+ if (!parse_func || !PyCallable_Check (parse_func )) {
32
31
goto cleanup;
33
32
}
34
33
@@ -45,14 +44,13 @@ extern "C" bool embit_miniscript_miniscript_parse(const char* input) {
45
44
}
46
45
47
46
// Add the input string to the tuple
48
- // PyTuple_SetItem steals a reference, so we don't need to decref input_str after
49
47
if (PyTuple_SetItem (args, 0 , input_str) < 0 ) {
50
48
goto cleanup;
51
49
}
52
50
input_str = NULL ; // Ownership transferred to args
53
51
54
52
// Call the Python function
55
- result = PyObject_CallObject (miniscript_parse_func , args);
53
+ result = PyObject_CallObject (parse_func , args);
56
54
if (!result) {
57
55
goto cleanup;
58
56
}
@@ -65,11 +63,19 @@ extern "C" bool embit_miniscript_miniscript_parse(const char* input) {
65
63
cleanup:
66
64
Py_XDECREF (result);
67
65
Py_XDECREF (args);
68
- Py_XDECREF (miniscript_parse_func );
66
+ Py_XDECREF (parse_func );
69
67
Py_XDECREF (main_module);
70
68
Py_XDECREF (input_str);
71
69
72
70
PyGILState_Release (gstate);
73
71
74
72
return success;
73
+ }
74
+
75
+ extern " C" bool embit_miniscript_miniscript_parse (const char * input) {
76
+ return call_python_parser (input, " miniscript_parse" );
77
+ }
78
+
79
+ extern " C" bool embit_descriptor_parse (const char * input) {
80
+ return call_python_parser (input, " descriptor_parse" );
75
81
}
0 commit comments