github.com/searKing/golang/go@v1.2.117/unsafe/translator.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build ignore 6 7 package unsafe 8 9 // #include <stdlib.h> 10 //enum { 11 // sizeofPtr = sizeof(void*), 12 //}; 13 import "C" 14 import ( 15 "reflect" 16 "unsafe" 17 ) 18 19 // CStringArray You can write as this directly. 20 // 21 // // []string -> [](*C.char) 22 // var strs []string 23 // cCharArray := make([]*C.char, 0, len(strs)) 24 // for _, s := range strs { 25 // char := (*C.char)(unsafe.Pointer(C.CString(s))) 26 // cCharArray = append(cCharArray, char) 27 // defer C.free(unsafe.Pointer(char)) //ιζΎε ε 28 // } 29 // var cstr **C.char 30 // var cstrSize C.int 31 // cstr = (**C.char)(unsafe.Pointer(&cCharArray[0])) 32 // cstrSize = C.int(len(strs)) 33 func CStringArray(strs ...string) (**C.char, C.int) { 34 // []string -> [](*C.char) 35 totalLen := len(strs) * C.sizeofPtr 36 for _, s := range strs { 37 totalLen += len(s) 38 } 39 cCharArrayBuf := C.malloc(C.size_t(totalLen)) 40 cCharArray := make([]*C.char, 0, len(strs)) 41 for _, s := range strs { 42 cCharArray = append(cCharArray, (*C.char)(unsafe.Pointer(C.CString(s)))) 43 } 44 //return (**C.char)(unsafe.Pointer(&cCharArray[0])), C.int(len(strs)) 45 return (**C.char)(unsafe.Pointer(cCharArrayBuf)), C.int(len(strs)) 46 } 47 48 // GoStringArray char** -> []string 49 func GoStringArray(strArray unsafe.Pointer, n int) []string { 50 // char** -> [](C.*char) 51 cCharArray := make([]*C.char, n) 52 header := (*reflect.SliceHeader)(unsafe.Pointer(&cCharArray)) 53 header.Cap = n 54 header.Len = n 55 header.Data = uintptr(strArray) 56 57 // [](C.*char) -> []string 58 strs := make([]string, 0, n) 59 for _, s := range cCharArray { 60 strs = append(strs, C.GoString(s)) 61 } 62 return strs 63 } 64 65 //// []unsafe.Pointer -> ** unsafe.Pointer 66 //func CPointerArray(strs []unsafe.Pointer) (*unsafe.Pointer, C.int) { 67 // return (*unsafe.Pointer)(unsafe.Pointer(&strs[0])), C.int(len(strs)) 68 //} 69 // 70 //// char** -> []interface{} 71 //func GoPointerArray(pointerArray *unsafe.Pointer, n int) []unsafe.Pointer { 72 // cPointerArray := make([]unsafe.Pointer, n) 73 // header := (*reflect.SliceHeader)(unsafe.Pointer(&cPointerArray)) 74 // header.Cap = n 75 // header.Len = n 76 // header.Data = uintptr(unsafe.Pointer(pointerArray)) 77 // return cPointerArray 78 //} 79 // 80 //func CAnyArray(strs []interface{}) (*unsafe.Pointer, C.int) { 81 // return (*unsafe.Pointer)(unsafe.Pointer(&strs[0])), C.int(len(strs)) 82 //} 83 // 84 //// char** -> []interface{} 85 //func GoAnyArray(anyArray *unsafe.Pointer, n int) []interface{} { 86 // cAnyArray := make([]interface{}, n) 87 // header := (*reflect.SliceHeader)(unsafe.Pointer(&cAnyArray)) 88 // header.Cap = n 89 // header.Len = n 90 // header.Data = uintptr(unsafe.Pointer(anyArray)) 91 // return cAnyArray 92 //}