This is a creation in Article, where the information may have evolved or changed.
How do I use the same custom data type in two different package? This is mainly for the type of struct included in the C header file, which is well handled if you are only customizing the data type in a different go package. But in fact the core of the process is the same, the following two examples to illustrate the solution.
Test Routines Directory
├── include│ └── data.h└── src ├── common │ └── common.go └── main └── main.go
Test
Data.h
#pragma once#include <stdio.h>struct Data { int a; char b;};
Common.go
package common/*#include <stdio.h>#cgo CFLAGS : -I../../include#include "data.h"*/import"C"import ( "fmt")funcbool { fmt.Printf("data : %d %c\n", data.a, data.b) returntrue}
Main.go
package main/*#include <stdio.h>#cgo CFLAGS : -I../../include#include "data.h"*/import"C"import ( "common")func main() { data := C.struct_Data{a: C.int(2), b: C.char('b')} common.Print(&data)}
$go run main.go
Error occurred
.\main.go:19: cannot use &data (type *C.struct_Data) as type *common.C.structin argument to common.Print
Error resolution method
Method One
By changing the member variable name of the connector body in Data.h to the start of capitalization. type GData C.struct_Data
you can then use the type directly in Comm.go, and then into Main.go common.GData
, without having to include the Data.h header file again in Main.go.
package mainimport ( "common" "fmt")func main() { data := common.GData{A: 2'b'} fmt.Println(data) common.Print(&data)}
Method Two
The first way we can do this is by modifying the data.h header file, but what if we don't have permission to modify the content of Data.h? That is, the member variable of the struct in data.h is named or starts with lowercase.
The first thing to know is that in different package, include the same header file in the data type, and then use this data type to pass to another package in the function will report the above error. The second way to do this is to use the Set/get method. Re-write Common.go and Main.go:
Common.go
package common/*# Include <stdio.h> #cgo CFLAGS:-I.. /.. /include#include "data.h" */ import "C" Span class= "Hljs-keyword" >import ( "FMT" ) type< /span> GData c.struct_datafunc (Data *gdata) Gdataseta (a int ) {data.a = C.int (A)} func (Data *gdata) Gdatasetb (b byte ) {data.b = C.char (b)}func Print (data *gdata) bool {fmt. Printf ( "data:%d%c\n" , DATA.A, data.b) return Span class= "Hljs-constant" >true }
Main.go
package mainimport ( "common")func main() { data := common.GData{} data.GDataSetA(2) data.GDataSetB('b') common.Print(&data)}
This unifies the same data type, that is, the Gdata type in the common package.