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 11.C_ByteSliceToCharPtr #10

Merged
merged 1 commit into from
Mar 17, 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
15 changes: 15 additions & 0 deletions 11.C_ByteSliceToCharPtr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# C.ByteSliceToCharPtr

```C.CBytes()```を用いずに、```[]byte```を```(char *)```に変換するには以下の手順を踏む。

1. スライスの先頭要素のポインタを取得
1. ```unsafe.Pointer```を取得
1. (*C.char)にキャスト

cgoでは、```unsafe.Pointer``` がCの ```(void *)``` に当たる。

Cの ```(void *)``` と同様に、```unsafe.Pointer``` も任意のポインタ型にキャストできる。

Cでは配列は「先頭要素のポインタ」を表しているが、Goではそれが出来ない。

なので、明示的に先頭要素のポインタを指定する必要がある。
8 changes: 8 additions & 0 deletions 11.C_ByteSliceToCharPtr/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
39 changes: 39 additions & 0 deletions 11.C_ByteSliceToCharPtr/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

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

const int BUF_SIZE = 11;

void setBuf(char *buf) {
strncpy(buf, "helloworld", BUF_SIZE);
}
*/
import "C"
import (
"encoding/hex"
"fmt"
"unsafe"
)

func main() {
var (
buf = make([]byte, int(C.BUF_SIZE))
bufPtr = unsafe.Pointer(&buf[0]) //明示的に先頭要素のポインタを渡す
charPtr = (*C.char)(bufPtr) // (void *) --> (char *)
printBuf = func() {
fmt.Println(string(buf))
fmt.Println(hex.Dump(buf))
}
)

printBuf()

// C側の宣言では (char *) を引数に要求しているため、unsafe.Pointer を *C.char にキャストして渡す.
// unsafe.Pointer は、 (void *) を表すので、任意のポインタ型にキャスト可能.
C.setBuf(charPtr)

printBuf()
}