@@ -50,10 +50,7 @@ namespace cpp2py {
5050 // C++ type -> Python Type
5151 using conv_table_t = std::map<std::string, PyTypeObject *>;
5252
53- // Each translation holds a shared pointer to the converter table
54- static std::shared_ptr<conv_table_t > conv_table_sptr = {};
55-
56- // Access the table of the wrapped types, and creates if it does not exists.
53+ // Fetch the pointer to the converter table from __main__
5754 inline std::shared_ptr<conv_table_t > get_conv_table_from_main () {
5855 // Fetch __main__ module
5956 pyref mod = PyImport_GetModule (PyUnicode_FromString (" __main__" ));
@@ -72,23 +69,23 @@ namespace cpp2py {
7269 return {*static_cast <std::shared_ptr<conv_table_t > *>(ptr)};
7370 }
7471
75- // Destructor used to clean the capsule later
72+ // Destructor used to clean the capsule containing the converter table pointer
7673 inline void _table_destructor (PyObject *capsule) {
7774 auto *p = static_cast <std::shared_ptr<conv_table_t > *>(PyCapsule_GetPointer (capsule, " __main__.__cpp2py_table" ));
7875 delete p;
7976 }
8077
81- // Initialize the converter table
82- inline void init_conv_table () {
83- conv_table_sptr = get_conv_table_from_main ();
78+ // Get the converter table, initialize it if necessary
79+ inline static std::shared_ptr< conv_table_t > get_conv_table () {
80+ std::shared_ptr< conv_table_t > sptr = get_conv_table_from_main ();
8481
8582 // Init map if pointer in main is null
86- if (not conv_table_sptr ){
87- conv_table_sptr = std::make_shared<conv_table_t >();
83+ if (not sptr ){
84+ sptr = std::make_shared<conv_table_t >();
8885
8986 // Now register the pointer in __main__
9087 PyObject * mod = PyImport_GetModule (PyUnicode_FromString (" __main__" ));
91- auto * p = new std::shared_ptr<conv_table_t >{conv_table_sptr };
88+ auto * p = new std::shared_ptr<conv_table_t >{sptr };
9289 pyref c = PyCapsule_New ((void *)p, " __main__.__cpp2py_table" , (PyCapsule_Destructor)_table_destructor);
9390 pyref s = PyUnicode_FromString (" __cpp2py_table" );
9491 int err = PyObject_SetAttr (mod, s, c);
@@ -97,8 +94,12 @@ namespace cpp2py {
9794 throw std::runtime_error (" Can not add the __cpp2py_table to main" );
9895 }
9996 }
97+ return sptr;
10098 }
10199
100+ // Each translation holds a shared pointer to the converter table
101+ static const std::shared_ptr<conv_table_t > conv_table_sptr = get_conv_table();
102+
102103 // get the PyTypeObject from the table in __main__.
103104 // if the type was not wrapped, return nullptr and set up a Python exception
104105 inline PyTypeObject *get_type_ptr (std::type_index const &ind) {
0 commit comments