|
| 1 | +#include "processor/wetext_processor_c_api.h" |
| 2 | + |
| 3 | +#include <cstring> |
| 4 | +#include <memory> |
| 5 | +#include <string> |
| 6 | +#include <utility> |
| 7 | + |
| 8 | +#include "processor/wetext_processor.h" |
| 9 | + |
| 10 | +using wetext::Processor; |
| 11 | + |
| 12 | +// Utility ------------------------------------------------------------------ |
| 13 | +namespace { |
| 14 | +// Copies an std::string into a newly allocated C string that the caller must |
| 15 | +// free via wetext_free_string(). |
| 16 | +const char* CopyToCString(const std::string& str) { |
| 17 | + char* out = new char[str.size() + 1]; |
| 18 | + std::memcpy(out, str.c_str(), str.size() + 1); |
| 19 | + return out; |
| 20 | +} |
| 21 | +} // namespace |
| 22 | + |
| 23 | +// Public API --------------------------------------------------------------- |
| 24 | + |
| 25 | +WetextProcessorHandle wetext_create_processor(const char* tagger_path, |
| 26 | + const char* verbalizer_path) { |
| 27 | + if (!tagger_path || !verbalizer_path) { |
| 28 | + return nullptr; |
| 29 | + } |
| 30 | + try { |
| 31 | + Processor* proc = new Processor(tagger_path, verbalizer_path); |
| 32 | + return static_cast<WetextProcessorHandle>(proc); |
| 33 | + } catch (...) { |
| 34 | + return nullptr; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +void wetext_destroy_processor(WetextProcessorHandle handle) { |
| 39 | + if (!handle) return; |
| 40 | + Processor* proc = static_cast<Processor*>(handle); |
| 41 | + delete proc; |
| 42 | +} |
| 43 | + |
| 44 | +#define WETEXT_RETURN_STRING(expr) \ |
| 45 | + if (!handle || !input) return nullptr; \ |
| 46 | + Processor* proc = static_cast<Processor*>(handle); \ |
| 47 | + std::string result = (expr); \ |
| 48 | + return CopyToCString(result); |
| 49 | + |
| 50 | +const char* wetext_tag(WetextProcessorHandle handle, const char* input) { |
| 51 | + WETEXT_RETURN_STRING(proc->Tag(input)); |
| 52 | +} |
| 53 | + |
| 54 | +const char* wetext_verbalize(WetextProcessorHandle handle, const char* input) { |
| 55 | + WETEXT_RETURN_STRING(proc->Verbalize(input)); |
| 56 | +} |
| 57 | + |
| 58 | +const char* wetext_normalize(WetextProcessorHandle handle, const char* input) { |
| 59 | + WETEXT_RETURN_STRING(proc->Normalize(input)); |
| 60 | +} |
| 61 | + |
| 62 | +void wetext_free_string(const char* str) { |
| 63 | + delete[] str; |
| 64 | +} |
0 commit comments