Skip to content

Commit

Permalink
Merge pull request #8 from devlights/add-c-stringn
Browse files Browse the repository at this point in the history
  • Loading branch information
devlights authored Mar 17, 2024
2 parents b653d61 + 6ffbee9 commit 2366079
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
3 changes: 3 additions & 0 deletions 09.C_GoStringN/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# C.GoStringN

```C.GoStringN()```は、```C.GoString()```のサイズ指定版。
8 changes: 8 additions & 0 deletions 09.C_GoStringN/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
49 changes: 49 additions & 0 deletions 09.C_GoStringN/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package main

/*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *cStr = "hello C World";
void pStr(const char *m) {
printf("%s (char *)\n", m);
}
*/
import "C"
import (
"fmt"
"unsafe"
)

func main() {
//
// Goの文字列をC側の文字列にするには C.CString() を使う
// C側の文字列をGoの文字列にするには C.GoString() を使う
// C側の文字列をサイズ指定でGoの文字列にするには C.GoStringN() を使う
//

//
// Go -> C
//
var (
goStr = "hello Go World"
cStr = C.CString(goStr)
)
defer C.free(unsafe.Pointer(cStr))

C.pStr(cStr)

//
// C -> Go
//
var (
cStr2 = C.cStr
goStr2 = C.GoString(cStr2)
goStr3 = C.GoStringN(cStr2, 5)
)

fmt.Printf("%[1]v (%[1]T)\n", goStr2)
fmt.Printf("%[1]v (%[1]T)\n", goStr3)
}

0 comments on commit 2366079

Please sign in to comment.