-
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 #25 from devlights/add-c-struct-typedef-example
- Loading branch information
Showing
3 changed files
with
76 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,31 @@ | ||
# これは何? | ||
|
||
cgoにてC側で構造体を定義して利用する場合 | ||
|
||
```c | ||
struct A { ... }; | ||
``` | ||
と | ||
```c | ||
typedef struct A TA; | ||
``` | ||
|
||
では、Go側での宣言で指定する型が異なるというサンプルです。 | ||
|
||
```struct A { ... };``` とした場合は | ||
|
||
```go | ||
var a C.struct_(構造体名) | ||
``` | ||
|
||
と宣言します。 | ||
|
||
```typedef struct A TA;``` とした場合は | ||
|
||
```go | ||
var ta C.TA | ||
``` | ||
|
||
と宣言します。 |
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 . |
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,37 @@ | ||
package main | ||
|
||
/* | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
struct A { | ||
int value; | ||
}; | ||
typedef struct A TA; | ||
void p(const struct A *a) { | ||
printf("value=%d\n", a->value); | ||
} | ||
*/ | ||
import "C" | ||
|
||
func main() { | ||
var ( | ||
a C.struct_A // typedefしていない構造体は C.struct_(構造体名) という型となる | ||
ta C.TA // typedefしているものは C.型名 でアクセス可能 | ||
) | ||
|
||
// | ||
// struct A {}; と定義した場合は以下のような展開となる。 | ||
// type _Ctype_struct_A struct { ... } | ||
// typedef struct A TA; と定義した場合は以下のような展開となる。 | ||
// type _Ctype_TA = _Ctype_struct_A | ||
// | ||
|
||
a.value = C.int(10) | ||
ta.value = C.int(20) | ||
|
||
C.p(&a) | ||
C.p(&ta) | ||
} |