OpenccFmmsegLib 1.5.0
See the version list below for details.
dotnet add package OpenccFmmsegLib --version 1.5.0
NuGet\Install-Package OpenccFmmsegLib -Version 1.5.0
<PackageReference Include="OpenccFmmsegLib" Version="1.5.0" />
<PackageVersion Include="OpenccFmmsegLib" Version="1.5.0" />
<PackageReference Include="OpenccFmmsegLib" />
paket add OpenccFmmsegLib --version 1.5.0
#r "nuget: OpenccFmmsegLib, 1.5.0"
#:package OpenccFmmsegLib@1.5.0
#addin nuget:?package=OpenccFmmsegLib&version=1.5.0
#tool nuget:?package=OpenccFmmsegLib&version=1.5.0
OpenccFmmsegLib
A .NET Standard 2.0 library providing a managed C# wrapper for the Rust-based opencc-fmmseg C API (OpenCC-compatible), enabling high-performance Chinese text conversion (Simplified / Traditional) in .NET applications.
This library focuses only on OpenCC-style conversion. For Jieba segmentation and keyword extraction, use OpenccJiebaLib instead.
This README describes the public API for v1.5.0, bundled with native opencc-fmmseg-capi v0.13.1.
Features
- OpenCC-compatible Chinese text conversion (Simplified / Traditional variants)
- Optional punctuation conversion
- Fast FMM-based segmentation engine under the hood (native Rust)
- Lightweight API with explicit native error-reporting semantics
- Safe native resource management via
IDisposable - Immutable custom dictionaries with typed slots and append/override modes
- Optional native compatibility normalization and DeTofu display fallback
Supported Conversion Configurations
s2t, t2s, s2tw, tw2s, s2twp, tw2sp, s2hk, s2hkp,
hk2s, hk2sp, t2tw, t2twp, t2hk, t2hkp, tw2t, tw2tp,
hk2t, hk2tp, t2jp, jp2t, s2seal, t2seal, seal2s, seal2t
The phrase-aware Hong Kong configurations s2hkp, hk2sp, t2hkp, and
hk2tp require native opencc-fmmseg-capi v0.11.5 or later.
All bundled native runtimes use opencc-fmmseg-capi v0.13.1.
The Small Seal Script configurations require native v0.13.0 or later and support both typed and
case-insensitive string APIs: OpenccConfig.S2SEAL (21), T2SEAL (22), SEAL2S (23), and SEAL2T (24).
For example:
using var converter = new OpenccFmmseg();
string seal = converter.Convert("小篆", OpenccConfig.T2SEAL);
string traditional = converter.Convert(seal, "seal2t");
Displaying the resulting Small Seal Script characters requires a font that supports them.
Getting Started
Prerequisites
- A .NET runtime that supports .NET Standard 2.0 and a shipped native platform/architecture
- Examples use C# 8 or later (
using var); older language versions can use ausingblock - Native
opencc_fmmseg_capilibrary available at runtime
Installation
Option 1 — From NuGet (recommended)
dotnet add package OpenccFmmsegLib
The NuGet package includes prebuilt native runtimes and deploys them under:
runtimes/<RID>/native/
Shipped RIDs:
win-x64linux-arm64linux-x64osx-x64osx-arm64
No manual copying is required when using NuGet.
Option 2 — Project Reference / Custom Native Builds
The package source organizes native assets using this layout:
runtimes/<RID>/native/
Expected filenames:
- Windows:
opencc_fmmseg_capi.dll - Linux:
libopencc_fmmseg_capi.so - macOS:
libopencc_fmmseg_capi.dylib
This wrapper uses standard P/Invoke library resolution and has no custom native loader.
For project references and custom builds, copy the native file next to the application executable
or configure the platform native-library search path. A runtimes/<RID>/native/ folder alone
does not guarantee discovery outside NuGet runtime asset resolution.
🧪 Unit test projects must also have access to the native library. Copy it next to the test assembly when using a project reference, as this repository does for Windows x64 tests.
Usage
using OpenccFmmsegLib;
using var opencc = new OpenccFmmseg();
string input = "汉字转换测试";
string result = opencc.Convert(input, "s2t");
Console.WriteLine(result); // 漢字轉換測試
int code = opencc.ZhoCheck(input);
Console.WriteLine(code); // 2 (Simplified Chinese)
Custom Dictionaries
Create a converter with one or more in-memory dictionaries. All existing conversion methods use the custom mappings; configuration remains selected per conversion call.
using System.Collections.Generic;
using OpenccFmmsegLib;
var customDictionarySpecifications = new[]
{
new CustomDictSpec(
DictSlot.STPhrases,
CustomDictMode.Append,
new Dictionary<string, string>
{
["汉字转换"] = "自訂轉換",
["自定义词语"] = "自訂詞語"
}),
new CustomDictSpec(
DictSlot.TSPhrases,
CustomDictMode.Append,
new Dictionary<string, string> { ["自訂詞語"] = "自定义词语" })
};
using var converter = new OpenccFmmseg(customDictionarySpecifications);
string result = converter.Convert("汉字转换", "s2t"); // 自訂轉換
string reverse = converter.Convert("自訂詞語", OpenccConfig.T2S); // 自定义词语
Append merges entries into the selected built-in slot, replacing mappings for matching source keys.
Override clears that entire slot before adding the supplied entries; other slots retain their mappings.
For example, overriding STCharacters with only 汉 → 訂 makes 汉龙 convert to 訂龙 under s2t.
Use append when you want to preserve the remaining built-in mappings.
Select a slot used by your conversion pipeline: STCharacters/STPhrases for s2t,
TSCharacters/TSPhrases for t2s, or the appropriate Taiwan, Hong Kong, Japanese, or punctuation slot
for regional conversions. Punctuation mappings require punctuation: true.
Slot IDs are explicit native identifiers, separate from OpenccConfig IDs.
Specifications and their entries are applied in input order. Later duplicate keys win; a later override
clears mappings added earlier to that slot. An ordered IEnumerable<KeyValuePair<string, string>>
can express duplicate keys. CustomDictSpec copies entries into a read-only snapshot. The converter
copies the dictionary data into native ownership during construction, so caller collection changes
and later garbage collection cannot affect it. Dictionaries cannot be mutated after initialization,
and separate converter instances have independent custom mappings.
An empty specification collection is equivalent to the default constructor. An empty entry collection leaves an appended slot unchanged or clears an overridden slot. Null collections, null specifications, null source/target strings, embedded NUL characters, invalid UTF-16, and undefined slot/mode values are rejected. Entries are literal mappings, without file-format parsing or target-token splitting. Empty source/target strings are forwarded according to native dictionary semantics.
Custom construction requires native opencc_new_custom (v0.11.5 or later).
All 25 slots in the checked-in header are exposed and supported by every bundled v0.13.1 runtime:
Windows x64, Linux x64/ARM64, and macOS x64/ARM64. The four Seal* slots require native v0.13.0 or
later. If you supply an older custom native library, requesting an unsupported slot throws
InvalidOperationException with the native error. Both typed and string conversion APIs support all 24
configurations, including Seal configuration IDs 21–24.
Temporary UTF-8 buffers are pinned only during initialization and released on success or failure. Custom construction adds no work to conversion hot paths and introduces no new dependencies.
Compatibility Normalization and DeTofu
These optional operations require native v0.12.0 or later, supported by all bundled v0.13.1 runtimes. They are instance methods because each native C function requires a live OpenCC instance. The recommended processing order is normalization, Chinese conversion, then display fallback:
using OpenccFmmsegLib;
string input = "金庸小說";
using var converter = new OpenccFmmseg();
string normalized = converter.NormalizeCompatExtended(input);
string converted = converter.Convert(normalized, "s2t");
string result = converter.DeTofu(converted, DeTofuLevel.ExtB);
NormalizeCompat(text) normalizes mapped CJK Compatibility Ideographs, including supplementary-plane
characters: 金庸 becomes 金庸, and 天龍八部書 becomes 天龍八部書.
NormalizeCompatExtended(text) additionally applies the native curated Unicode compatibility mappings;
for example, 聼竒羙䂖甁噐 becomes 聽奇美石瓶器, while the basic method leaves that text unchanged.
These methods use the native tables and are not general-purpose NFC, NFD, NFKC, or NFKD normalization.
Characters without applicable mappings remain unchanged.
DeTofu(text, level) uses the native built-in fallback table to improve display compatibility when a font
or reader cannot render rare CJK characters. For example, 骖𬴂 becomes 骖騑 at DeTofuLevel.ExtB.
It is a display fallback, not a linguistic conversion, and leaves characters without applicable mappings
unchanged, including unmapped supplementary characters. It does not insert question marks or replacement glyphs.
| Level | Native value | Eligible mappings (inclusive) |
|---|---|---|
ExtB |
0 | Extension B through I |
ExtC |
1 | Extension C through I |
ExtD |
2 | Extension D through I |
ExtE |
3 | Extension E through I |
ExtF |
4 | Extension F through I |
ExtG |
5 | Extension G through I |
ExtH |
6 | Extension H through I |
ExtI |
7 | Extension I only |
The selected threshold determines eligibility; replacement still requires an entry in the built-in table.
ExtB is the broadest threshold. There is no disabled level; omit the DeTofu call to disable fallback.
All three methods return an empty string for null or empty input on a live converter. Undefined DeTofu
levels throw ArgumentOutOfRangeException, including for empty input. Embedded NUL characters are rejected
with ArgumentException to prevent native string truncation. Calls after disposal throw ObjectDisposedException,
including for null or empty input. Native failures throw InvalidOperationException with the native diagnostic;
allocated native output and rented input buffers are released on both success and failure.
Normalization and DeTofu are explicitly opt-in. Normal Convert() behavior and custom dictionary configuration
remain unchanged; none of these operations runs automatically during conversion.
Error Handling
- Constructors, normalization, DeTofu, and
ConvertCfgToUtf8ZthrowInvalidOperationExceptionon native failure. ConvertandConvertCfgpreserve the native string-returning contract: native errors can be returned as text, and a null native output pointer becomes an empty string. They do not uniformly throw on native errors.TryConvertCfgToUtf8returnsfalsefor insufficient capacity or native failure; see its buffer contract below.- Missing, incompatible, or older custom native libraries can cause
DllNotFoundException,BadImageFormatException, orEntryPointNotFoundException. ObjectDisposedExceptionis thrown by instance APIs after disposal, including for null or empty input.OpenccFmmseg.LastError()returns the last native error for the calling thread. Read it immediately after the failing native call, on the same thread, before anawaitor any other native OpenCC call on that thread.
Public API Overview
Input and validation contracts
On a live converter, null or empty text returns an empty string (Convert, ConvertCfg, normalization,
DeTofu), zero (ZhoCheck), or a single NUL byte (UTF-8 output). Conversion methods skip configuration
validation for null or empty input. DeTofu validates its level even for empty input. Disposal is checked first.
For nonempty input, Convert(string, string, bool) validates the managed canonical name and
Convert(string, OpenccConfig, bool) throws ArgumentOutOfRangeException for an undefined enum value.
Both ConvertCfg overloads delegate ID validation to native code, including undefined enum values.
Names are case-insensitive but do not accept whitespace, paths, .json suffixes, or numeric strings.
The enum default value, zero, is not a valid configuration; use OpenccConfigExtensions.DefaultConfig().
Convert, ConvertCfg, and ZhoCheck pass NUL-terminated input: embedded NUL characters truncate
native input. Normalization and DeTofu reject embedded NUL. The explicit-length UTF-8 APIs pass the full
input length; output can contain embedded NUL bytes, so use byte counts when decoding it.
Ordinary text APIs use .NET UTF-8 replacement fallback for invalid UTF-16; custom dictionary entries
are validated strictly instead.
OpenccFmmseg
OpenccFmmseg()Creates a converter using the built-in dictionaries.OpenccFmmseg(IEnumerable<CustomDictSpec> customDictionarySpecifications)Creates an immutable converter with ordered custom dictionary specifications. See Custom Dictionaries for merge behavior and native requirements.string NormalizeCompat(string text)Normalizes mapped CJK Compatibility Ideographs using the native table.string NormalizeCompatExtended(string text)Adds the native curated Unicode compatibility mappings to basic normalization.string DeTofu(string text, DeTofuLevel level)Applies optional native display fallback at an inclusive CJK extension threshold.string Convert(string input, string config, bool punctuation = false)Converts text using a case-insensitive canonical name; validates names for nonempty input.string Convert(string input, OpenccConfig configId, bool punctuation = false)Converts text using a typed configuration; validates enum values for nonempty input.string ConvertCfg(string input, OpenccConfig configId, bool punctuation = false)Converts Chinese text using the numeric-config native path with a typed config enum.string ConvertCfg(string input, int configNum, bool punctuation = false)Advanced interop overload using a numeric configuration ID. Validation is delegated to the native library; invalid IDs return native error text and setLastError(). Hidden from IntelliSense.string ConvertCfgMemLen(string input, int configId, bool punctuation = false)Obsolete and hidden from IntelliSense. Uses the specialized explicit-length native buffer pipeline. PreferConvertCfg()for ordinary conversion; this API's size-query and output passes add conversion overhead.byte[] ConvertCfgToUtf8Z(string input, int configId, bool punctuation = false)Returns a newly allocated UTF-8 byte array including a trailing NUL terminator for interop scenarios. Uses the explicit-length native size-query and output passes; null or empty input returns a single NUL byte.
bool TryConvertCfgToUtf8(string input, int configId, bool punctuation, Span<byte> destination, out int requiredBytes)
Writes NUL-terminated UTF-8 output into a caller-provided buffer using the explicit-length native API.
requiredBytes includes the trailing NUL byte, including for null or empty input (one byte).
byte[] ConvertCfgMemLenToUtf8Z(string input, int configId, bool punctuation = false)Obsolete alias forConvertCfgToUtf8Z(); hidden from IntelliSense.
bool TryConvertCfgToUtf8Into(string input, int configId, bool punctuation, Span<byte> destination, out int requiredBytes)
Obsolete alias for TryConvertCfgToUtf8(); hidden from IntelliSense.
For TryConvertCfgToUtf8() and its legacy alias, false with requiredBytes > destination.Length
means the buffer is too small; resize and retry. This is the expected result for an empty-buffer size query and is not a
native error. For other false results, retrieve
LastError() immediately on the same thread.
Example of caller-owned UTF-8 output (requires using System; and using System.Text;):
using var converter = new OpenccFmmseg();
Span<byte> destination = stackalloc byte[256];
if (!converter.TryConvertCfgToUtf8("汉字", (int)OpenccConfig.S2T, false,
destination, out int requiredBytes))
{
if (requiredBytes <= destination.Length)
throw new InvalidOperationException(OpenccFmmseg.LastError());
destination = new byte[requiredBytes];
if (!converter.TryConvertCfgToUtf8("汉字", (int)OpenccConfig.S2T, false,
destination, out requiredBytes))
throw new InvalidOperationException(OpenccFmmseg.LastError());
}
string text = Encoding.UTF8.GetString(destination.Slice(0, requiredBytes - 1).ToArray());
Only use destination contents on success. Required sizes include the final NUL; exclude that one byte
when decoding. Required sizes greater than Int32.MaxValue throw OverflowException.
int ZhoCheck(string input)Detects non-Chinese (0), Traditional Chinese (1), or Simplified Chinese (2) text.static int GetNativeAbiNumber()Returns the native binary interface version for compatibility diagnostics.static string GetNativeVersionString()Returns the native library's semantic version string for logging and diagnostics.static bool ConfigNameToIdNative(string name, out OpenccConfig configId)Attempts a case-insensitive configuration-name lookup using the native library.static bool ConfigIdToNameNative(OpenccConfig configId, out string name)Attempts to retrieve a canonical lowercase configuration name using the native library.
The native configuration helpers are intended for interop/debugging and do not set the native last-error state.
Prefer the managed OpenccConfigExtensions helpers for ordinary configuration parsing and formatting.
static string LastError()Returns the last error message reported by the native library for the calling thread.void Dispose()ImplementsIDisposablefor deterministic native resource cleanup; repeated calls are safe.
OpenccConfigExtensions
These helpers are pure managed code and do not require loading the native library. Configuration names are case-insensitive and otherwise must match a supported canonical name.
static OpenccConfig DefaultConfig()Returns the managed default,OpenccConfig.S2T.static bool TryParseConfig(string name, out OpenccConfig configId)Returns whether a name is supported; on failure, setsconfigIdtodefault.static OpenccConfig Parse(string name)Parses a supported name; throwsArgumentNullExceptionfor null orArgumentExceptionfor an unsupported name.static bool IsValidConfig(string name)Tests whether a name is supported without throwing.static bool TryGetConfigName(OpenccConfig configId, out string name)Returns a canonical lowercase name, orfalsewith an empty string for an undefined ID.static string ToCanonicalName(this OpenccConfig config)Extension method returning a canonical lowercase name; throwsArgumentOutOfRangeExceptionfor an undefined ID.
Custom dictionary specifications
CustomDictSpec(DictSlot slot, CustomDictMode mode, IEnumerable<KeyValuePair<string, string>> entries)Copies ordered mappings into an immutable specification, validating the slot, mode, and entries.DictSlot Slot { get; },CustomDictMode Mode { get; }Expose the selected dictionary slot and merge mode.IReadOnlyList<KeyValuePair<string, string>> Entries { get; }Exposes the read-only snapshot of mappings in input order.
Public enums
OpenccConfigDefines all 24 numeric conversion IDs, includingS2SEAL,T2SEAL,SEAL2S, andSEAL2T. See Supported Conversion Configurations.DictSlot : uintDefines all 25 native dictionary slots, includingSealCharacters,SealCharactersRev,SealVariants, andSealVariantsRev. See Custom Dictionaries.CustomDictMode : uintDefinesAppend(1) to merge entries andOverride(2) to clear a slot before applying entries.DeTofuLevel : uintDefines inclusive display-fallback thresholds fromExtB(0) throughExtI(7). See Compatibility Normalization and DeTofu.
Troubleshooting
DllNotFoundException / Unable to load shared library 'opencc_fmmseg_capi'
Ensure the native file exists under:
runtimes/<RID>/native/Clean and rebuild the project after installing via NuGet
Verify the correct file name for your platform
BadImageFormatException
- Architecture mismatch (x64 vs x86)
- Ensure your application and native library target the same architecture
Linux: library exists but cannot be loaded
Place the
.sonext to the executable or set:export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(pwd)
macOS: Gatekeeper / quarantine issues
xattr -dr com.apple.quarantine libopencc_fmmseg_capi.dylib
Thread Safety
- Do not use a single
OpenccFmmseginstance concurrently across threads, including during disposal - Create one instance per thread or scope
- Dispose instances promptly (
usingis recommended)
License
MIT License. See LICENSE.
Acknowledgements
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- System.Memory (>= 4.6.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
v1.5.0
New Features:
- Added four Small Seal Script conversion configurations: s2seal, t2seal, seal2s, and seal2t (IDs 21-24).
- Added Small Seal Script support to both typed OpenccConfig and string-based conversion APIs.
- Added CustomDictSpec, DictSlot, and CustomDictMode for strongly typed custom dictionary configuration.
- Added a new OpenccFmmseg constructor accepting multiple ordered custom dictionary specifications.
- Added Append and Override modes for extending or replacing individual native dictionary slots.
- Added support for all 25 native dictionary slots, including four Small Seal Script slots.
- Added NormalizeCompat() for standard CJK Compatibility Ideograph normalization.
- Added NormalizeCompatExtended() for extended CJK compatibility normalization.
- Added DeTofu() with a strongly typed DeTofuLevel enum and inclusive fallback thresholds.
- Exposed normalization and DeTofu as instance methods using the existing native converter.
Native Interop and Memory Safety:
- Added P/Invoke bindings for native custom dictionary initialization, normalization, and DeTofu.
- Implemented CustomDictionaryMarshaller with safe UTF-8 encoding and pinned managed buffers.
- Added sequential native structure layouts with pointer-sized array counts.
- Added deterministic cleanup of pinned dictionary buffers on success and failure.
- Added validation for dictionary slots, modes, null entries, embedded NUL characters, and invalid UTF-16.
- Preserved native error messages when custom dictionary initialization fails.
- Reused existing UTF-8 marshalling and native string cleanup infrastructure.
- Preserved native converter ownership and disposal behavior.
Unicode and Text Processing:
- Added native-backed standard and extended CJK compatibility normalization.
- Added configurable DeTofu fallback for supported CJK Unicode extensions.
- Preserved unmapped characters according to native transformation semantics.
- Supported supplementary-plane Unicode characters in normalization and fallback operations.
- Documented the optional Normalize -> Convert -> DeTofu processing pipeline.
- Kept normalization and DeTofu explicitly opt-in without changing existing conversion behavior.
Native Runtime Updates:
- Updated all bundled native opencc_fmmseg_capi runtimes to v0.13.1.
- Enabled native support for all 25 dictionary slots, including Small Seal Script slots.
- Aligned bundled native libraries with the new custom dictionary and Unicode transformation APIs.
Testing and Validation:
- Added 32 custom dictionary regression tests covering Append, Override, validation, and native failures.
- Added 28 additional regression tests for normalization, DeTofu, and Unicode behavior.
- Added coverage for native error propagation, buffer cleanup, and recovery after initialization failures.
- Added tests for supplementary Unicode characters, fallback levels, and invalid inputs.
- Resolved ReSharper disposable lifetime warnings in custom dictionary tests.
- Passed all 101 tests in Windows x64 Release configuration.
- Preserved netstandard2.0 compatibility.
- Linux, macOS, and ARM64 execution have not been independently tested locally.
Documentation and Compatibility:
- Expanded XML documentation for all new public APIs and enum members.
- Added README examples for custom dictionaries, Unicode normalization, and DeTofu.
- Updated release documentation with native version requirements and usage guidance.
- Preserved existing constructors, conversion overloads, and public API behavior.
- Avoided additional overhead in existing conversion hot paths.
- Maintained backward compatibility with existing managed consumers.