4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[go] cgoは使いたくないけど、C.GoBytes() は使いたいみたいなー [追記あり]

Last updated at Posted at 2014-11-10

cgo は結構万能だけど、これを使うと、Windows の場合、ビルドの際、MinGW gcc が必要になりそうな雰囲気である。これでは多くの pull request が期待できないッ。でも、C.GoBytes() とか、C.GoStringN() を使いたいッ。この気持ちッ、天に届け!

でけた! できてへん

var msvcrt = syscall.NewLazyDLL("msvcrt")
var memcpy = msvcrt.NewProc("memcpy")

func CGoBytes(p, length uintptr) []byte {
	buffer := make([]byte, length)
	memcpy.Call(uintptr(unsafe.Pointer(&buffer[0])), p, length)
	return buffer
}

func CGoStringN(p, length uintptr) string {
	return string(CGoBytes(p, length))
}

これではうまくいかない

  • length が 0 の時に panic を起こす
    • これについては if length <= 0 { return []byte{} } すれば Ok
  • Ctrl-C ハンドラがうまく動作しなくなる
    • import "C" を入れるだけで動作するようになる、なぜ?

ということで、C.GoBytes は不要にはなりましたが、import "C" だけは必要という、あまり意味のない状態で、現在に至ります。わからんなー

import "C" せずに Ctrl-C ハンドラを正常動作させる回避策

kernel32.dllSetConsoleCtrlHandler を使わないようにしたら、Ctrl-C がキャッチできるようになった。理由はよくわからないが、シグナル関係が Windows 版 Go ではまだきちんと実装されていないことが関係しているのだろうか…

関係URL

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?