Search code examples
goenumscgo

Can't find struct's some field with pragma pack, 64 bits integer


package main

/*
#include <inttypes.h> 
#pragma pack(1)
typedef struct _sss {
uint64_t some; // ok
uint32_t wow; // ok
uint64_t some2; // not found
uint64_t some3; // not found
uint64_t some4; // not found
uint32_t some5; // ok
} Type;
#pragma pack()
*/
import "C"
import (
    "fmt"
)

func main() {
    s := C.Type{}
    s.some = 10; 
    s.wow = 10; 
    s.some2 = 10; 
    s.some5 = 10;
    fmt.Println("Hello, playground")
}


I declared struct named C.Type.

If pragma pack(1) and 64 bits members are used together.

╭─dire@dire-81w4 ~/workspace
╰─go run test.go                                                                                                                    2 ↵
# command-line-arguments
./test.go:25:6: s.some2 undefined (type _Ctype_struct__sss has no field or method some2)

Compilation is possible by removing pragma pack(1).

Go 1.15 version is being used. Do you know why?


Solution

  • I found answer about my question.

    If the fields of a C struct are aligned such that they can't be represented by a Go struct, then they cannot be accessed directly from cgo. You will have to write functions in C to read and write those fields.

    I nowdays am too busy to comment. It's late, but it's answered.