objective-c - iOS - 如何调用 C 函数?

标签 objective-c ios c memory-management

我想用这个函数来帮助监控内存:

void print_free_memory ()
{
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;

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;

if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS)
    NSLog(@"Failed to fetch vm statistics");

/* Stats in bytes */
natural_t mem_used = (vm_stat.active_count +
                      vm_stat.inactive_count +
                      vm_stat.wire_count) * pagesize;
natural_t mem_free = vm_stat.free_count * pagesize;
natural_t mem_total = mem_used + mem_free;
NSLog(@"used: %u free: %u total: %u", mem_used, mem_free, mem_total);
}

一个。我应将此函数放在我的 Xcode 项目中的什么位置?

B.我怎么调用它?显然,我想设置为持续监控内存。

最佳答案

A. Where do I put this function in my Xcode project?

将定义放在单独的 .c 文件中,将声明放在单独的头文件中。

PrintFreeMem.h

extern void print_free_memory();

PrintFreeMem.c

#include "PrintFreeMem.h"
void print_free_memory() {
    // Your implementation
}

B. How do I call it?

在包含其头文件后,您可以像调用常规 C 函数一样调用它:

#include "PrintFreeMem.h"

-(void)myMethod {
    ...
    print_free_memory();
}

关于objective-c - iOS - 如何调用 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11999669/

相关文章:

c - 如何在C中对单个字符执行scanf

ios - UIPopoverController 在 iOS 8 中显示为 modalViewController

ios - 从消息弹出窗口导航到 RootViewController 时应用程序崩溃

c# - Xamarin.iOS 上的蓝牙请求权限

ios - 计时器运行时 SwiftUI 警报不会消失

c - 当您意外运行无限循环时会发生什么样的错误

ios - Sprite Kit - 检测接触

ios - twilio iOS Sdk 中的 Twilio 来电问题

ios - 从 Objective-C AppDelegate 调用时,Swift UIViewController init 不执行

c - 向字符串添加 header 并使用 TCP 套接字发送