Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add 13.C_PointerArithmetic #12

Merged
merged 1 commit into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions 13.C_PointerArithmetic/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# C.PointerArithmetic

これは、cgoに特化した内容ではないが、C言語ではポインタ演算が可能であり、それなりに利用されている。

Goでは基本的にポインタ演算が禁止されている。

が、```unsafe```パッケージと```uintptr```を用いることで、一応可能となる。

しかし、これらはGoの世界から大きく離脱した行為となるため、基本的にやるべきではない。(https://stackoverflow.com/a/32701024)
8 changes: 8 additions & 0 deletions 13.C_PointerArithmetic/Taskfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# https://taskfile.dev

version: '3'

tasks:
default:
cmds:
- go run main.go
35 changes: 35 additions & 0 deletions 13.C_PointerArithmetic/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

/*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void p(const void *v) {
char *m = (char *)v;
printf("%s\n", m);
}
*/
import "C"
import "unsafe"

func main() {
var (
goStr = "hello Go World"
cStr = C.CString(goStr)
cStrPtr = unsafe.Pointer(cStr)
)
defer C.free(cStrPtr)

C.p(cStrPtr)

// uintptr に変換することでポインタ演算が可能となる
// 演算後を再度 unsafe.Pointer にする
//
// 以下はメモリアドレスを6バイト進めたポインタを取得している
var (
offsetPtr = unsafe.Pointer(uintptr(cStrPtr) + 6)
)

C.p(offsetPtr)
}