我正在尝试将以下代码转换为Swift:
{
// Set up the variables
double totalUsedMemory = 0.00;
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;
// Get the variable values
host_port = mach_host_self();
host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
host_page_size(host_port, &pagesize);
vm_statistics_data_t vm_stat;
// Check for any system errors
if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
// Error, failed to get Virtual memory info
return -1;
}
// Memory statistics in bytes
natural_t usedMemory = (natural_t)((vm_stat.active_count +
vm_stat.inactive_count +
vm_stat.wire_count) * pagesize);
natural_t allMemory = [self totalMemory];
return usedMemory;
}
我的Swift代码是:
{
// Set up the variables
var totalUsedMemory: Double = 0.00
var host_port: mach_port_t
var host_size: mach_msg_type_number_t
var pagesize:vm_size_t
// Get the variable values
host_port = mach_host_self()
host_size = mach_msg_type_number_t(MemoryLayout<vm_statistics_data_t>.stride / MemoryLayout<integer_t>.stride)
// host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
host_page_size(host_port, &pagesize);
var vm_stat: vm_statistics_data_t ;
// Check for any system errors
if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
// Error, failed to get Virtual memory info
return -1;
}
// Memory statistics in bytes
var usedMemory: Int64 = (Int64)((vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count) * pagesize);
return usedMemory;
}
我收到了这两个错误:
**二元运算符'&amp;'不能应用于'(host_info_t).Type'(又名'UnsafeMutablePointer.Type')和'vm_statistics_data_t'(又名'vm_statistics')
类型的操作数
在此声明中 host_statistics(host_port,HOST_VM_INFO,(host_info_t)&amp; vm_stat,&amp; host_size)
和
二进制运算符'*'不能应用于'UInt32'和'vm_size_t'类型的操作数(又名'UInt')**
在此声明中 - var usedMemory:Int64 =(Int64)((vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count)* pagesize);
答案 0 :(得分:3)
对于指针类型,Swift比C更严格,这使得与这样的函数交互成为一种真正的痛苦,这些函数希望你将指针传递给除了你所依据的事物的实际类型以外的类型。试图传递给函数。所以我同意评论者的意见,你可能最好将这个功能留在(Objective-)C中。但是,如果您绝对 转换为Swift,那么您可能需要执行以下操作:
// Initialize a blank vm_statistics_data_t
var vm_stat = vm_statistics_data_t()
// Get a raw pointer to vm_stat
let err: kern_return_t = withUnsafeMutableBytes(of: &vm_stat) {
// Bind the raw buffer to Int32, since that's what host_statistics
// seems to want a pointer to.
let boundBuffer = $0.bindMemory(to: Int32.self)
// Call host_statistics, and return its status out of the closure.
return host_statistics(host_port, HOST_VM_INFO, boundBuffer.baseAddress, &host_size)
}
// Now take a look at what we got and compare it against KERN_SUCCESS
if err != KERN_SUCCESS {
// Error, failed to get Virtual memory info
return -1;
}