Opencc Memory Leak

近期專案上有個需求,需要使用opencc來將接收到的資料將簡體轉繁體,參考了will保哥與黑暗執行緒的範例,其中保哥的文章指出有做防止記憶體洩漏的調整,但上線後發現一樣有記憶體洩漏的問題,最後找到的解決方案是,應該要使用opencc的函式做記憶體釋放,而非使用C#的函式。 調整前 using System.Runtime.InteropServices; using System.Text; public static class OpenCCHelper { [DllImport(@"C:\Tools\opencc\bin\opencc.dll", EntryPoint = "opencc_open")] private static extern IntPtr opencc_open(string configFileName); [DllImport(@"C:\Tools\opencc\bin\opencc.dll", EntryPoint = "opencc_convert_utf8")] private static extern IntPtr opencc_convert_utf8(IntPtr opencc, IntPtr input, long length); public static string ConvertFromSimplifiedToTraditional(this string text, string config = "s2t") { return OpenCC(text, config: config); } public static string ConvertFromSimplifiedToTraditionalTaiwan(this string text, string config = "s2twp") { return OpenCC(text, config: config); } public static string ConvertFromTraditionalTaiwanToSimplified(this string text, string config = "tw2sp") { return OpenCC(text, config: config); } public static string ConvertFromTraditionalToSimplified(this string text, string config = "t2s") { return OpenCC(text, config: config); } public static string OpenCC(this string text, string config) { var configFile = $"C:\\Tools\\OpenCC\\share\\opencc\\{config}....

May 19, 2024