Skip to content

Instantly share code, notes, and snippets.

@hnaohiro
Created January 19, 2013 13:51
Show Gist options
  • Save hnaohiro/4572778 to your computer and use it in GitHub Desktop.
Save hnaohiro/4572778 to your computer and use it in GitHub Desktop.
Golangでincovを使うサンプル
package main
/*
#include <stdlib.h>
#include <iconv.h>
#cgo LDFLAGS: -liconv
*/
import "C"
import (
"unsafe"
)
type Iconv struct {
pointer C.iconv_t
}
func Open(tocode, fromcode string) (*Iconv, error) {
cs_tocode := C.CString(tocode)
defer C.free(unsafe.Pointer(cs_tocode))
cs_fromcode := C.CString(fromcode)
defer C.free(unsafe.Pointer(cs_fromcode))
iconv, err := C.iconv_open(cs_tocode, cs_fromcode)
if err != nil {
return nil, err
}
return &Iconv{iconv}, nil
}
func (iconv *Iconv) Close() error {
_, err := C.iconv_close(iconv.pointer)
return err
}
func (iconv *Iconv) Convert(inbuf []byte) ([]byte, error) {
if len(inbuf) == 0 {
return inbuf, nil
}
inbytes := C.size_t(len(inbuf))
outbuf := make([]byte, inbytes*6)
outbytes := C.size_t(len(outbuf))
inptr := (*C.char)(unsafe.Pointer(&inbuf[0]))
outptr := (*C.char)(unsafe.Pointer(&outbuf[0]))
_, err := C.iconv(iconv.pointer, &inptr, &inbytes, &outptr, &outbytes)
if err != nil {
return nil, err
}
return outbuf[:len(outbuf)-int(outbytes)], nil
}
func ConvertEncoding(input, fromcode, tocode string) (string, error) {
iconv, err := Open(fromcode, tocode)
if err != nil {
return "", err
}
defer iconv.Close()
b, err := iconv.Convert([]byte(input))
if err != nil {
return "", err
}
return string(b), nil
}
func main() {
text := "てすと"
text_sjis, _ := ConvertEncoding(text, "UTF-8", "Shift-JIS")
println(text_sjis)
text_utf8, _ := ConvertEncoding(text_sjis, "Shift-JIS", "UTF-8")
println(text_utf8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment