From a3fa57d58f71012ac94915d4dd05c22ffbfda702 Mon Sep 17 00:00:00 2001 From: Dave Abrahams Date: Fri, 17 Nov 2000 20:22:30 +0000 Subject: [PATCH] Added module name retrieval for pickling support [SVN r8246] --- module.cpp | 19 ++++++++++++++++--- module.h | 10 +++++++--- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/module.cpp b/module.cpp index 53fe1ec6..4605b787 100644 --- a/module.cpp +++ b/module.cpp @@ -10,9 +10,23 @@ namespace py { +namespace { + Ptr name_holder; +} + +String Module::name() +{ + // If this fails, you haven't created a Module object + assert(name_holder.get() != 0); + return String(name_holder); +} + Module::Module(const char* name) : m_module(Py_InitModule(const_cast(name), initial_methods)) { + // If this fails, you've created more than 1 Module object in your module + assert(name_holder.get() == 0); + name_holder = Ptr(PyObject_GetAttrString(m_module, "__name__")); } void @@ -24,14 +38,13 @@ Module::add(Function* x, const char* name) void Module::add(Ptr x, const char* name) { - PyObject* dictionary = PyModule_GetDict( m_module ); + PyObject* dictionary = PyModule_GetDict(m_module); PyDict_SetItemString(dictionary, const_cast(name), x.get()); } void Module::add(PyTypeObject* x, const char* name /*= 0*/) { - this->add(Ptr(as_object(x)), - name ? name : x->tp_name); + this->add(Ptr(as_object(x)), name ? name : x->tp_name); } PyMethodDef Module::initial_methods[] = { { 0, 0, 0, 0 } }; diff --git a/module.h b/module.h index 368c4411..7daee935 100644 --- a/module.h +++ b/module.h @@ -11,6 +11,7 @@ # include "pyconfig.h" # include "pyptr.h" +# include "objects.h" # include "functions.h" namespace py { @@ -19,13 +20,13 @@ class Module { typedef PyObject * (*RawFunctionPtr)(py::Tuple const &, py::Dict const &); -public: + public: + // Create a module. REQUIRES: only one Module is created per module. Module(const char* name); + // Add elements to the module void add(Function* x, const char* name); - void add(PyTypeObject* x, const char* name = 0); - void add(Ptr x, const char*name); template @@ -39,6 +40,9 @@ public: { add(new_wrapped_function(fn), name); } + + static String name(); + private: PyObject* m_module; static PyMethodDef initial_methods[1];