我使用以下C代码片段来获取OS X上的CPU负载:
#include <mach/message.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
[...]
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
kern_return_t error;
host_cpu_load_info_data_t r_load;
mach_port_t host_port = mach_host_self();
error = host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&r_load, &count);
阅读cgo教程后,我尝试将这段代码移植到Go上。产生的代码如下所示:
package main
/*
#include <stdlib.h>
#include <mach/message.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
*/
import "C"
func main() {
var err C.kern_return_t
var host_info_out C.host_info_t
var host_port C.mach_port_t = C.mach_host_self()
count := C.mach_msg_type_number_t(C.HOST_CPU_LOAD_INFO_COUNT)
err = C.host_statistics(C.host_t(host_port), C.HOST_CPU_LOAD_INFO, &host_info_out, &count)
}
但是,当我尝试构建代码时,最终出现以下错误消息
go build cputimes.go
# command-line-arguments
cputimes.go:33: cannot use &host_info_out (type *_Ctype_host_info_t) as type *_Ctype_integer_t in function argument
我不理解为什么cgo提示这种类型。在mach header 中将host_statistics()的签名定义为:
kern_return_t host_statistics
(
host_t host_priv,
host_flavor_t flavor,
host_info_t host_info_out,
mach_msg_type_number_t *host_info_outCnt
);
最佳答案
函数原型(prototype)说,在示例程序中传递指向host_statistics
变量的指针时,host_info_t
的第三个参数是host_info_t
变量。
查看 mach/host_info.h
header file,我们可以看到host_info_t
是指针类型:
typedef integer_t *host_info_t; /* varying array of int. */
这就解释了为什么收到有关
integer_t
类型不匹配的错误消息的原因。在处理该参数时,您的Go代码看起来实际上并不等同于C代码。您可能想要这样的东西:
...
var r_load C.host_cpu_load_info_data_t
...
err = C.host_statistics(C.host_t(host_port), C.HOST_CPU_LOAD_INFO, C.host_info_t(unsafe.Pointer(&r_load)), &count)
...
(您需要使用
unsafe
包在不兼容的指针类型之间进行转换)。关于go - GoLang/CGO : Problems calling Mach API host_statistics() from Go,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19123059/