Created
September 21, 2013 07:42
-
-
Save hnakamur/6648237 to your computer and use it in GitHub Desktop.
unsafeでポインタを使って構造体のプライベートフィールドの値を書き換える例。
unsafeを使っているので http://play.golang.org/ では試せず、ローカルで実行する必要があります。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"unsafe" | |
) | |
/* | |
void modifyN(void* p, int n) { | |
*(int *)p = n; | |
} | |
*/ | |
import "C" | |
type Piyo struct { | |
n int | |
} | |
func main() { | |
piyo := &Piyo{10} | |
p := unsafe.Pointer(&piyo.n) | |
fmt.Printf("%d\n", piyo.n) | |
C.modifyN(p, 2) | |
fmt.Printf("%d\n", piyo.n) | |
// Output: | |
// 10 | |
// 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cgoを使ったプログラムの実行モジュールはlibcに依存します。
参考:cgoを使わないプログラムの例
hello.go