如何在iOS上的Unity3d中获得大量"免费"内存?

Max*_*kov 1 c# objective-c unity-game-engine ios

我有一个问题:如果我尝试使用Texture2D.ReadPixels创建屏幕截图,游戏会在某些设备上崩溃(最值得注意的是,iPod 4G).据说,它是因为内存不足而发生的.在创建屏幕截图之前,我想检测一下,如果我可以安全地分配所需的内存量,并且如果我想我会崩溃就向玩家显示警告.

但是,似乎纹理之类的资源是在Mono VM之外进行管理的.当我有大约16mb的地图集时,System.GC.GetTotalMemory返回9mb.所以,似乎我必须为此编写一个插件.

(有一节描述我没有收到低内存警告,但似乎我错了,在Objective-C级别,警告成功提出).

如何在不崩溃的情况下获得可以分配的"免费"内存量?可能有其他方法来实现我想要的功能吗?

Tec*_*eks 6

解释你自己的答案:这不是客观的C代码,而是普通的旧C,使用Mach API来从内核获取统计信息.Mach API是由XNU导出的低级API,它是由顶层(导出BSD API,如我们知道并喜欢UN*X的常用系统调用)和底层(即Mach)组成的混合内核.该代码使用Mach"host"抽象,其中(除其他外)提供有关资源的OS级别利用率的统计信息.

具体来说,这是一个完整的注释:

#import <mach/mach.h>       // Required for generic Mach typedefs, like the mach_port_t
#import <mach/mach_host.h>  // Required for the host abstraction APIs.

extern "C" // C, rather than objective-c
{

    const int HWUtils_getFreeMemory()
    {
        mach_port_t host_port;             
        mach_msg_type_number_t host_size;
        vm_size_t pagesize;

        // First, get a reference to the host port. Any task can do that, and this
        // requires no privileges
        host_port = mach_host_self();
        host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);

        // Get host page size - usually 4K
        host_page_size(host_port, &pagesize);

        vm_statistics_data_t vm_stat;

        // Call host_statistics, requesting VM information. 

        if (host_statistics(host_port,  // As obtained from mach_host_self()
             HOST_VM_INFO,              // Flavor - many more in <mach/host_info.h>(host_info_t)&vm_stat,                  // OUT - this will be populated
             &host_size)                // in/out - sizeof(vm_stat). 
              != KERN_SUCCESS)         
            NSLog(@"Failed to fetch vm statistics"); // log error

        /* Stats in bytes */
        // Calculating total and used just to show all available functionality

        // This part is basic math. Counts are all in pages, so multiply by pagesize
        // Memory used is sum of active pages, (resident, used)
        //                       inactive,      (resident, but not recently used)
        //                   and wired (locked in memory, e.g. kernel)

        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);


        return (int) mem_free;
    }
Run Code Online (Sandbox Code Playgroud)