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

我正在关注从golang调用objective-c代码的教程。教程在这个链接


代码如下(教程上也一样)


main.go


package main


import (

    "fmt"

    "net/url"

    "strconv"

    "unsafe"

)


//#cgo CFLAGS: -x objective-c

//#cgo LDFLAGS: -framework Foundation

//#include "foundation.h"

import "C"


// NSString -> C string

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


// NSString -> Go string

func gostring(s *C.NSString) string { return C.GoString(cstring(s)) }


// NSNumber -> Go int

func goint(i *C.NSNumber) int { return int(C.nsnumber2int(i)) }


// NSArray length

func nsarraylen(arr *C.NSArray) uint { return uint(C.nsarraylen(arr)) }


// NSArray item

func nsarrayitem(arr *C.NSArray, i uint) unsafe.Pointer {

    return C.nsarrayitem(arr, C.ulong(i))

}


// NSURL -> Go url.URL

func 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.URL

func 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())

}


倚天杖
浏览 123回答 1
1回答

慕码人2483693

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) {&nbsp; &nbsp; if (s == NULL) { return NULL; }&nbsp; &nbsp; NSString *cs = *((__unsafe_unretained NSString **)(s));&nbsp; &nbsp; const char *cstr = [cs UTF8String];&nbsp; &nbsp; return cstr;}在main.goGo 代码函数中,它需要C.NSString作为unsafe.Pointerto传递nsstring2cstring(void*)// NSString -> C stringfunc cstring(s *C.NSString) *C.char { return C.nsstring2cstring(unsafe.Pointer(s)) }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go