Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created September 21, 2013 07:42
Show Gist options
  • Save hnakamur/6648237 to your computer and use it in GitHub Desktop.
Save hnakamur/6648237 to your computer and use it in GitHub Desktop.
unsafeでポインタを使って構造体のプライベートフィールドの値を書き換える例。 unsafeを使っているので http://play.golang.org/ では試せず、ローカルで実行する必要があります。
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
}
@hnakamur
Copy link
Author

cgoを使ったプログラムの実行モジュールはlibcに依存します。

[vagrant@cent64 modify_private_field]$ file modify_private_field
modify_private_field: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped
[vagrant@cent64 modify_private_field]$ ldd ./modify_private_field
    linux-vdso.so.1 =>  (0x00007fff5e3ff000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f697aa8d000)
    libc.so.6 => /lib64/libc.so.6 (0x00007f697a6fa000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f697acb5000)

参考:cgoを使わないプログラムの例

hello.go

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, world!")
}
[vagrant@cent64 hello]$ go build
[vagrant@cent64 hello]$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
[vagrant@cent64 hello]$ ldd hello
    not a dynamic executable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment