Go生成库给C/C++
Windows
- main.go
package main
/*
#include <stdlib.h>
*/
import "C"
import (
"net"
"unsafe"
)
//export GetMacAddr
func GetMacAddr(ipaddr *C.char) (addr *C.char) {
var netIP net.IP
ip := C.GoString(ipaddr)
if netIP = net.ParseIP(ip); netIP == nil {
return
}
interfaces, err := net.Interfaces()
if err != nil || len(interfaces) == 0 {
return
}
for _, ifs := range interfaces {
addrs, err := ifs.Addrs()
if err != nil || ifs.HardwareAddr == nil {
continue
}
if addr == nil && len(ifs.HardwareAddr) > 0 {
addr = C.CString(ifs.HardwareAddr.String())
}
for _, a := range addrs {
_, ipNet, err := net.ParseCIDR(a.String())
if err != nil {
continue
}
if ipNet.Contains(netIP) {
C.free(unsafe.Pointer(addr))
return C.CString(ifs.HardwareAddr.String())
}
}
}
return
}
//export FreeCGOPtr
func FreeCGOPtr(p *C.char) {
C.free(unsafe.Pointer(p))
}
func main() {}
go build -ldflags "-s -w" -buildmode=c-shared -o mac_addr.dll main.go
生成 mac_addr.dll
和mac_addr.h
, 然后编写def文件
- mac_addr.def
EXPORTS
GetMacAddr
通过def文件生成lib文件
lib.exe /machine:X64 /def:mac_addr.def
这时候会得到 mac_addr.lib
, mac_addr.dll
, mac_addr.h
三个文件
Linux
go build -ldflags "-w -s" -buildmode=c-archive -o mac_addr.a main.go
生成 mac_addr.a
和mac_addr.h
gcc main.c -O3 mac_addr.a -lpthread