Golang, CGO, double pointers and macos Foundation framework

Viewed 37

First, I have some basic C experience, but not too fluent with CGO and macos programming

I write a function, that removes a file in a system Trash. I have a working code, that I try to improve

The code first:

package trash

/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation
#import "trash.h"
*/
import "C"
import (
    "errors"
    "unsafe"
)

// TrashItem puts items into system trash
func TrashItem(filePath string) error {
    cString := C.CString(filePath)
    defer C.free(unsafe.Pointer(cString))

    var cErr = new(C.Error)

    res := C.TrashItem(cString, cErr)
    if res == 0 {
        // convert cErr to go error
        return errors.New("...")
    }

    return nil
}
#import <Foundation/Foundation.h>

typedef struct _Error {
    long C;
    const char *E;
} Error;

const BOOL TrashItem(const char *filePath, Error *error);

(I googled a lot to write this code, not sure, how good it is)

#import "trash.h"

const BOOL TrashItem(const char *filePath, Error *error) {
    NSFileManager *manager = [NSFileManager defaultManager];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:@(filePath)];

    NSError *e;
    BOOL success = [manager trashItemAtURL:fileURL resultingItemURL:nil error:&e];
    if (!success) {
        error->C = e.code;
        error->E = [e.localizedDescription UTF8String];
    }

    return success;
}

First issue:

I don't wont to always initialize var cErr = new(C.Error). I think I could make trash function accept Error **error, but I struggle to pass double pointer from go to C (I have go pointer have go pointer error)

Second issue:

I would like to avoid custom Error struct and pass NSError * and access fields from go side.

I had Incompatible pointer types passing 'struct NSError *' to parameter of type 'NSError *, but https://stackoverflow.com/a/60715306/889530 solved it for me

But I think I still need NSError **, so I can read the data back, and again I struggle with void and double pointers here.

Can somebody explain me how to do that properly

0 Answers
Related