From fd1f18c48e6fbec50e8c908552c446c60363a94b Mon Sep 17 00:00:00 2001 From: Peng Wu Date: Fri, 30 Sep 2011 10:54:25 +0800 Subject: [PATCH] add lazy init --- src/PYLibPinyin.cc | 45 ++++++++++++++++++++++++++++++++++++++++----- src/PYLibPinyin.h | 5 +++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/PYLibPinyin.cc b/src/PYLibPinyin.cc index e4d1b84..a7097fe 100644 --- a/src/PYLibPinyin.cc +++ b/src/PYLibPinyin.cc @@ -30,24 +30,59 @@ std::unique_ptr LibPinyinBackEnd::m_instance; static LibPinyinBackEnd libpinyin_backend; LibPinyinBackEnd::LibPinyinBackEnd () { - m_pinyin_context = pinyin_init ("/usr/share/libpinyin/data", NULL); - m_chewing_context = pinyin_init ("/usr/share/libpinyin/data", NULL); + m_pinyin_context = NULL; + m_chewing_context = NULL; } LibPinyinBackEnd::~LibPinyinBackEnd () { - pinyin_fini(m_pinyin_context); - pinyin_fini(m_chewing_context); + if (m_pinyin_context) + pinyin_fini(m_pinyin_context); + m_pinyin_context = NULL; + if (m_chewing_context) + pinyin_fini(m_chewing_context); + m_chewing_context = NULL; +} + +pinyin_instance_t * +LibPinyinBackEnd::allocPinyinInstance () +{ + if (NULL == m_pinyin_context) { + m_pinyin_context = pinyin_init ("/usr/share/libpinyin/data", NULL); + } + return pinyin_alloc_instance (m_pinyin_context); +} + +void +LibPinyinBackEnd::freePinyinInstance (pinyin_instance_t *instance) +{ + pinyin_free_instance (instance); +} + +pinyin_instance_t * +LibPinyinBackEnd::allocChewingInstance () +{ + if (NULL == m_chewing_context) { + m_chewing_context = pinyin_init ("/usr/share/libpinyin/data", NULL); + } + return pinyin_alloc_instance (m_chewing_context); +} + +void +LibPinyinBackEnd::freeChewingInstance (pinyin_instance_t *instance) +{ + pinyin_free_instance (instance); } void LibPinyinBackEnd::init (void) { g_assert (NULL == m_instance.get ()); LibPinyinBackEnd * backend = new LibPinyinBackEnd; - m_instance.reset(backend); + m_instance.reset (backend); } void LibPinyinBackEnd::finalize (void) { + m_instance.reset (); } /* Here are the fuzzy pinyin options conversion table. */ diff --git a/src/PYLibPinyin.h b/src/PYLibPinyin.h index 212bf53..44ed727 100644 --- a/src/PYLibPinyin.h +++ b/src/PYLibPinyin.h @@ -38,6 +38,11 @@ public: gboolean setPinyinOptions (Config *config); gboolean setChewingOptions (Config *config); + pinyin_instance_t *allocPinyinInstance (); + void freePinyinInstance (pinyin_instance_t *instance); + pinyin_instance_t *allocChewingInstance (); + void freeChewingInstance (pinyin_instance_t *instance); + /* use static initializer in C++. */ static LibPinyinBackEnd & instance (void) { return *m_instance; } -- 2.7.4