Skip to content

Commit

Permalink
Merge pull request #25 from devlights/add-c-struct-typedef-example
Browse files Browse the repository at this point in the history
  • Loading branch information
devlights authored Nov 11, 2024
2 parents 0992383 + ac89d05 commit 011799e
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
31 changes: 31 additions & 0 deletions 25.C_struct_not_typedef/README.md
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
```

と宣言します。
8 changes: 8 additions & 0 deletions 25.C_struct_not_typedef/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 .
37 changes: 37 additions & 0 deletions 25.C_struct_not_typedef/main.go
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)
}

0 comments on commit 011799e

Please sign in to comment.