-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #8 from devlights/add-c-stringn
- Loading branch information
Showing
3 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# C.GoStringN | ||
|
||
```C.GoStringN()```は、```C.GoString()```のサイズ指定版。 |
This file contains 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
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 |
This file contains 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
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) | ||
} |