Fix possible memory access violation in cgo code

This commit is contained in:
akiyosi 2024-06-10 22:39:04 +09:00
parent 0d7e950e2e
commit 9b6d1ad28e
2 changed files with 16 additions and 5 deletions

View file

@ -7,10 +7,12 @@ package editor
#include <stdlib.h> #include <stdlib.h>
*/ */
import "C" import "C"
import "unsafe"
//export GetOpeningFilepath //export GetOpeningFilepath
func GetOpeningFilepath(str *C.char) { func GetOpeningFilepath(str *C.char) {
goStr := C.GoString(str) goStr := C.GoString(str)
C.free(unsafe.Pointer(str))
editor.openingFileCh <- goStr editor.openingFileCh <- goStr
} }

View file

@ -14,8 +14,6 @@ const objcbridgeH = `void SetMyApplicationDelegate();`
const objcbridgeM = `#import <Cocoa/Cocoa.h> const objcbridgeM = `#import <Cocoa/Cocoa.h>
char *cFilename;
// Forward declaration of the Go function to be called from C // Forward declaration of the Go function to be called from C
extern void GetOpeningFilepath(char* str); extern void GetOpeningFilepath(char* str);
@ -29,9 +27,9 @@ extern void GetOpeningFilepath(char* str);
} }
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename { - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename {
char *utf8String = [filename UTF8String]; const char *utf8String = [filename UTF8String];
cFilename = strdup(utf8String); char *cStr = strdup(utf8String);
GetOpeningFilepath(cFilename); GetOpeningFilepath(cStr);
return YES; return YES;
} }
@ -53,6 +51,17 @@ func main() {
} }
func generateFile(filename, content string) { func generateFile(filename, content string) {
if _, err := os.Stat(filename); err == nil {
err = os.Remove(filename)
if err != nil {
fmt.Println("Error removing existing file:", err)
return
}
} else if !os.IsNotExist(err) {
fmt.Println("Error checking file existence:", err)
return
}
file, err := os.Create(filename) file, err := os.Create(filename)
if err != nil { if err != nil {
fmt.Println("Error creating file:", err) fmt.Println("Error creating file:", err)