我试图用golang包中的syscall调用WindowsAPI(尽量不要使用cgo)但我面临localAnimal.animalColor()();
我不知道如何访问uintptr有其地址的数据
这是我正在做的代码
uintptr
答案 0 :(得分:2)
例如,要从Windows API GetUdpTable
函数返回UDP地址表:
package main
import (
"encoding/binary"
"fmt"
"net"
"os"
"syscall"
"unsafe"
)
var (
kernel32, _ = syscall.LoadLibrary("kernel32")
libIphlpapi, _ = syscall.LoadLibrary("iphlpapi")
pGetUDPTable, _ = syscall.GetProcAddress(libIphlpapi, "GetUdpTable")
)
func GetUdpTable() ([]net.UDPAddr, error) {
var dwSize uint32
r1, _, e1 := syscall.Syscall(
pGetUDPTable,
3,
uintptr(0),
uintptr(unsafe.Pointer(&dwSize)),
0,
)
const retErrInsufficientBuffer = 122
if r1 != retErrInsufficientBuffer {
err := fmt.Errorf("GetUdpTable() failed with return values", r1, e1)
return nil, err
}
buf := make([]byte, dwSize)
r1, _, e1 = syscall.Syscall(
pGetUDPTable,
3,
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&dwSize)),
0,
)
if r1 != 0 {
err := fmt.Errorf("GetUdpTable() failed with return values", r1, e1)
return nil, err
}
// MIB_UDPROW structure
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366926.aspx
type MIB_UDPROW struct {
dwLocalAddr uint32
dwLocalPort uint32 // network byte order
}
// MIB_UDPTABLE structure
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366930.aspx
const ANY_SIZE = (1 << 30) / unsafe.Sizeof(MIB_UDPROW{})
type MIB_UDPTABLE struct {
dwNumEntries uint32
table [ANY_SIZE]MIB_UDPROW
}
p_MIB_UDPTABLE := (*MIB_UDPTABLE)(unsafe.Pointer(&buf[0]))
table := p_MIB_UDPTABLE.table[:p_MIB_UDPTABLE.dwNumEntries]
udps := make([]net.UDPAddr, len(table))
for i, row := range table {
var udp net.UDPAddr
udp.IP = make([]byte, 4)
binary.LittleEndian.PutUint32(udp.IP, row.dwLocalAddr)
udp.Port = int(uint16(row.dwLocalPort>>8 | row.dwLocalPort<<8))
udps[i] = udp
}
return udps, nil
}
func main() {
udpTable, err := GetUdpTable()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Println(len(udpTable))
for _, udpAddr := range udpTable {
fmt.Println(udpAddr.IP, udpAddr.Port)
}
}
输出:
29
192.168.1.2 137
192.168.56.1 137
192.168.1.2 138
192.168.56.1 138
192.168.1.2 443
0.0.0.0 500
127.0.0.1 1900
192.168.1.2 1900
192.168.56.1 1900
0.0.0.0 3702
0.0.0.0 3702
0.0.0.0 3702
0.0.0.0 3702
0.0.0.0 4500
0.0.0.0 5004
0.0.0.0 5005
0.0.0.0 5355
0.0.0.0 17500
192.168.1.2 21986
0.0.0.0 53521
0.0.0.0 54363
0.0.0.0 54364
192.168.1.2 55808
127.0.0.1 55809
0.0.0.0 59285
0.0.0.0 59287
0.0.0.0 59289
127.0.0.1 63042
0.0.0.0 58180