Golang中的string与C++中unicode字符互转

func Str2uft16ptr(str string)(p uintptr){//将字符串转为utf16指针
	e:=utf16.Encode([]rune(str))//转成unicode
	e=append(e, uint16(0))//添加末尾的0
	p=uintptr(unsafe.Pointer(&e[0]))//转成指针
	//p=uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(str)))
	return
}

func addbuf(buf []uint16,newcap int)(newbuf []uint16){
	newbuf=make([]uint16,newcap)
	copy(newbuf,buf)
	return
}

func Utf16prt2str(p uintptr)(str string){//将utf16指针转为字符串
	len:=0
	buf:=make([]uint16,64)
	for a:=(*(*uint16)(unsafe.Pointer(p)));a!=0;len++{
		if len>=cap(buf){
			buf=addbuf(buf,len*2)
		}
		buf[len]=a
		p+=2//uint16占2字节
		a=(*(*uint16)(unsafe.Pointer(p)))
	}
	str=string(utf16.Decode(buf[:len]))
	return
}

测试代码(Windows下)

func abort(funcname string, err error) {
	panic(funcname + " failed: " + err.Error())
}
func msgbox3(text,title string)(res int32){
	h, err := syscall.LoadLibrary("user32.dll")
	if err != nil {
		abort("LoadLibrary", err)
	}
	defer syscall.FreeLibrary(h)
	proc, err := syscall.GetProcAddress(h, "MessageBoxW")
	if err != nil {
		abort("GetProcAddress", err)
	}
	r,_,_:=syscall.Syscall6(uintptr(proc), 4, 0, Str2uft16ptr(text), Str2uft16ptr(title),3,0,0)
	res=int32(r)
	return
}
func main(){
	c,t:="你好","提示"
	pc,pt:=Str2uft16ptr(c),Str2uft16ptr(t)
	c,t=Utf16prt2str(pc),Utf16prt2str(pt)
	msgbox3(c,t)
}

你可能感兴趣的:(Go学习)