From 5fe7d6f01425406afdb42fc6d025536a9166c572 Mon Sep 17 00:00:00 2001 From: Sandro Hanea <40202887+sandrohanea@users.noreply.github.com> Date: Wed, 4 Jun 2025 23:13:20 +0200 Subject: [PATCH] Free OpenVINO path strings --- Whisper.net/WhisperFactory.cs | 3 ++- Whisper.net/WhisperProcessor.cs | 34 +++++++++++++++++++++------------ 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/Whisper.net/WhisperFactory.cs b/Whisper.net/WhisperFactory.cs index 01b88e169..c0490d2cf 100644 --- a/Whisper.net/WhisperFactory.cs +++ b/Whisper.net/WhisperFactory.cs @@ -67,7 +67,8 @@ private WhisperFactory(IWhisperProcessorModelLoader loader, bool delayInit) var systemInfoPtr = libraryLoaded.Value.NativeWhisper!.WhisperPrintSystemInfo(); var systemInfoStr = Marshal.PtrToStringAnsi(systemInfoPtr); - Marshal.FreeHGlobal(systemInfoPtr); + // The pointer returned by WhisperPrintSystemInfo points to a static + // buffer owned by the native library. Do not free it here. return systemInfoStr; } diff --git a/Whisper.net/WhisperProcessor.cs b/Whisper.net/WhisperProcessor.cs index 0aca52351..a56aca2a5 100755 --- a/Whisper.net/WhisperProcessor.cs +++ b/Whisper.net/WhisperProcessor.cs @@ -357,18 +357,28 @@ private unsafe Task ProcessInternalAsync(ReadOnlyMemory samples, Cancella private IntPtr GetWhisperState() { var state = nativeWhisper.Whisper_Init_State(currentWhisperContext); - if (RuntimeOptions.LoadedLibrary == RuntimeLibrary.OpenVino) - { - var modelPath = Marshal.StringToHGlobalAnsi(options.OpenVinoModelPath); - var device = Marshal.StringToHGlobalAnsi(options.OpenVinoDevice); - var cachePath = Marshal.StringToHGlobalAnsi(options.OpenVinoCacheDir); - nativeWhisper.Whisper_Ctx_Init_Openvino_Encoder_With_State( - options.ContextHandle, - state, - modelPath, - device, - cachePath); - } + if (RuntimeOptions.LoadedLibrary == RuntimeLibrary.OpenVino) + { + var modelPath = Marshal.StringToHGlobalAnsi(options.OpenVinoModelPath); + var device = Marshal.StringToHGlobalAnsi(options.OpenVinoDevice); + var cachePath = Marshal.StringToHGlobalAnsi(options.OpenVinoCacheDir); + + try + { + nativeWhisper.Whisper_Ctx_Init_Openvino_Encoder_With_State( + options.ContextHandle, + state, + modelPath, + device, + cachePath); + } + finally + { + Marshal.FreeHGlobal(modelPath); + Marshal.FreeHGlobal(device); + Marshal.FreeHGlobal(cachePath); + } + } return state; }