44	"fmt" 
55	"os" 
66	"path/filepath" 
7+ 	"runtime" 
78	"strings" 
89	"unsafe" 
910
@@ -20,10 +21,25 @@ type SDGGML struct {
2021}
2122
2223var  (
23- 	LoadModel  func (model , model_apth  string , options  []string , threads  int32 , diff  int ) int 
24- 	GenImage  func (text , negativeText  string , width , height , steps  int , seed  int64 , dst  string , cfgScale  float32 , srcImage  string , strength  float32 , maskImage  string , refImages  []string , refImagesCount  int ) int 
24+ 	LoadModel  func (model , model_apth  string , options  []uintptr , threads  int32 , diff  int ) int 
25+ 	GenImage    func (text , negativeText  string , width , height , steps  int , seed  int64 , dst  string , cfgScale  float32 , srcImage  string , strength  float32 , maskImage  string , refImages  []string , refImagesCount  int ) int 
2526)
2627
28+ // Copied from Purego internal/strings 
29+ // TODO: We should upstream sending []string 
30+ func  hasSuffix (s , suffix  string ) bool  {
31+ 	return  len (s ) >=  len (suffix ) &&  s [len (s )- len (suffix ):] ==  suffix 
32+ }
33+ 
34+ func  CString (name  string ) * byte  {
35+ 	if  hasSuffix (name , "\x00 " ) {
36+ 		return  & (* (* []byte )(unsafe .Pointer (& name )))[0 ]
37+ 	}
38+ 	b  :=  make ([]byte , len (name )+ 1 )
39+ 	copy (b , name )
40+ 	return  & b [0 ]
41+ }
42+ 
2743func  (sd  * SDGGML ) Load (opts  * pb.ModelOptions ) error  {
2844
2945	sd .threads  =  int (opts .Threads )
@@ -56,8 +72,14 @@ func (sd *SDGGML) Load(opts *pb.ModelOptions) error {
5672
5773	fmt .Fprintf (os .Stderr , "Options: %+v\n " , oo )
5874
59- 	options  :=  make ([]string , len (oo ), len (oo ) +  1 )
60- 	* (* uintptr )(unsafe .Add (unsafe .Pointer (& options ), uintptr (len (oo )))) =  0 
75+ 	// At the time of writing Purego doesn't recurse into slices and convert Go strings to pointers so we need to do that 
76+ 	var  keepAlive  []any 
77+ 	options  :=  make ([]uintptr , len (oo ), len (oo )+ 1 )
78+ 	for  i , op  :=  range  oo  {
79+ 		bytep  :=  CString (op )
80+ 		options [i ] =  uintptr (unsafe .Pointer (bytep ))
81+ 		keepAlive  =  append (keepAlive , bytep )
82+ 	}
6183
6284	sd .cfgScale  =  opts .CFGScale 
6385
@@ -66,6 +88,8 @@ func (sd *SDGGML) Load(opts *pb.ModelOptions) error {
6688		return  fmt .Errorf ("could not load model" )
6789	}
6890
91+ 	runtime .KeepAlive (keepAlive )
92+ 
6993	return  nil 
7094}
7195
@@ -89,7 +113,7 @@ func (sd *SDGGML) GenerateImage(opts *pb.GenerateImageRequest) error {
89113	}
90114
91115	refImagesCount  :=  len (opts .RefImages )
92- 	refImages  :=  make ([]string , refImagesCount , refImagesCount   +   1 )
116+ 	refImages  :=  make ([]string , refImagesCount , refImagesCount + 1 )
93117	copy (refImages , opts .RefImages )
94118	* (* uintptr )(unsafe .Add (unsafe .Pointer (& refImages ), refImagesCount )) =  0 
95119
0 commit comments