From 0be5399d5a7dd5ab8448b8888a90a2bba63281e8 Mon Sep 17 00:00:00 2001 From: Cyberhan123 <255542417@qq.com> Date: Thu, 11 Jun 2026 11:46:36 +0800 Subject: [PATCH] feat: add free_sd_images function to manage memory for C API --- include/stable-diffusion.h | 4 ++++ src/stable-diffusion.cpp | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 17596f849..2175f895a 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -491,6 +491,10 @@ SD_API bool preprocess_canny(sd_image_t image, SD_API const char* sd_commit(void); SD_API const char* sd_version(void); +// for C API, caller needs to call free_sd_images to free the memory after use +// This helps avoid CRT problems on Windows when memory is allocated in the library but freed in the caller, which may use a different CRT. +SD_API void free_sd_images(sd_image_t* result_images, int num_images); + #ifdef __cplusplus } #endif diff --git a/src/stable-diffusion.cpp b/src/stable-diffusion.cpp index 8ba4a463a..79c4db468 100644 --- a/src/stable-diffusion.cpp +++ b/src/stable-diffusion.cpp @@ -5570,3 +5570,18 @@ SD_API bool generate_video(sd_ctx_t* sd_ctx, } return true; } + +SD_API void free_sd_images(sd_image_t* result_images, int num_images) { + if (result_images == nullptr) { + return; + } + + for (int i = 0; i < num_images; ++i) { + if (result_images[i].data != nullptr) { + free(result_images[i].data); + result_images[i].data = nullptr; + } + } + + free(result_images); +} \ No newline at end of file