为了账号安全,请及时绑定邮箱和手机立即绑定

不兼容的指针类型将“struct NSArray *”传递给“NSArray *”类型的参数

不兼容的指针类型将“struct NSArray *”传递给“NSArray *”类型的参数

Go
倚天杖 2022-05-23 15:04:33
我正在关注从golang调用objective-c代码的教程。教程在这个链接代码如下(教程上也一样)main.gopackage mainimport (    "fmt"    "net/url"    "strconv"    "unsafe")//#cgo CFLAGS: -x objective-c//#cgo LDFLAGS: -framework Foundation//#include "foundation.h"import "C"// NSString -> C stringfunc cstring(s *C.NSString) *C.char { return C.nsstring2cstring(s) }// NSString -> Go stringfunc gostring(s *C.NSString) string { return C.GoString(cstring(s)) }// NSNumber -> Go intfunc goint(i *C.NSNumber) int { return int(C.nsnumber2int(i)) }// NSArray lengthfunc nsarraylen(arr *C.NSArray) uint { return uint(C.nsarraylen(arr)) }// NSArray itemfunc nsarrayitem(arr *C.NSArray, i uint) unsafe.Pointer {    return C.nsarrayitem(arr, C.ulong(i))}// NSURL -> Go url.URLfunc gourl(nsurlptr *C.NSURL) *url.URL {    nsurl := *C.nsurldata(nsurlptr)    userInfo := url.UserPassword(        gostring(nsurl.user),        gostring(nsurl.password),    )    host := gostring(nsurl.host)    if nsurl.port != nil {        port := goint(nsurl.port)        host = host + ":" + strconv.FormatInt(int64(port), 10)    }    return &url.URL{        Scheme:   gostring(nsurl.scheme),        User:     userInfo, // username and password information        Host:     host,     // host or host:port        Path:     gostring(nsurl.path),        RawQuery: gostring(nsurl.query),    // encoded query values, without '?'        Fragment: gostring(nsurl.fragment), // fragment for references, without '#'    }}// NSArray<NSURL> -> Go []url.URLfunc gourls(arr *C.NSArray) []url.URL {    var result []url.URL    length := nsarraylen(arr)    for i := uint(0); i < length; i++ {        nsurl := (*C.NSURL)(nsarrayitem(arr, i))        u := gourl(nsurl)        result = append(result, *u)    }    return result}func UserApplicationSupportDirectories() []url.URL {    return gourls(C.UserApplicationSupportDirectories())}func main() {    fmt.Printf("%#+v\n", UserApplicationSupportDirectories())}
查看完整描述

1 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

C.NSStringCGO 生成的与NSStringObjective-C 不兼容。为避免来自编译器的警告消息,例如 in const char* nsstring2cstring(),NSString应void*在您的 Objective-C 代码函数中作为 in 参数传递(foundation.m foundation.h),并将您的void*toNSString和返回为C const char*:


const char* nsstring2cstring(void* s) {

    if (s == NULL) { return NULL; }

    NSString *cs = *((__unsafe_unretained NSString **)(s));

    const char *cstr = [cs UTF8String];

    return cstr;

}

在main.goGo 代码函数中,它需要C.NSString作为unsafe.Pointerto传递nsstring2cstring(void*)


// NSString -> C string

func cstring(s *C.NSString) *C.char { return C.nsstring2cstring(unsafe.Pointer(s)) }


查看完整回答
反对 回复 2022-05-23
  • 1 回答
  • 0 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信