我正在关注从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())
}
慕码人2483693
相关分类