如何获取swift int变量的地址

时间:2015-01-28 03:02:55

标签: ios objective-c swift

我已经完成了以下操作,为Swift中的OpenAL分配缓冲区:

init() {
        self.buffers = NSMutableArray(capacity: 2);
        self.sources = NSMutableArray(capacity: 2);


        var sources: [ALuint] = [ALuint](count: 2, repeatedValue: 0);
        var buffers: [ALuint] = [ALuint](count: 2, repeatedValue: 0);
        alGenSources(2,  UnsafeMutablePointer<ALuint>(sources));
        alGenBuffers(2, UnsafeMutablePointer<ALuint>(buffers));

        for i in 0...2 {
            self.sources.addObject(NSNumber(unsignedInt: sources[i]));
            self.buffers.addObject(NSNumber(unsignedInt: buffers[i]));
        }
    }

它完美无缺。我无法弄清楚如何删除它。我试过了:

deinit {
        for i in 0...2 {
            var source = self.sources.objectAtIndex(i).unsignedIntValue;
            var buffer = self.buffers.objectAtIndex(i).unsignedIntValue;

            //Error below.. I can't get address of "source" or "buffer".
            alDeleteSources(1, UnsafePointer<ALuint>(ALuint(source)));
        }

        self.sources = nil; //cannot nil an NSMutableArray either..
        self.buffers = nil;
    }

那么如何获取源和缓冲区变量的地址以将其传递给UnsafePointer<ALuint>

我试图将下面的Objective-C代码翻译成上面的Swift代码:

-(void) init
{
    if (!_sources)
    {
        unsigned int sources[2];
        unsigned int buffers[2];
        alGenSources(2, &sources[0]);
        alGenBuffers(2, &buffers[0]);

        _sources = [[NSMutableArray alloc] initWithCapacity: 2];
        _buffers = [[NSMutableArray alloc] initWithCapacity: 2];

        for (int i = 0; i < 2; ++i)
        {
            [_sources addObject: [NSNumber numberWithUnsignedInt: sources[i]]];
            [_buffers addObject: [NSNumber numberWithUnsignedInt: buffers[i]]];
        }
    }
}

-(void) dealloc
{
    for (int i = 0; i < [_sources count]; ++i)
    {
        unsigned int source = [[_sources objectAtIndex: i] unsignedIntValue];
        unsigned int buffer = [[_buffers objectAtIndex: i] unsignedIntValue];

        alDeleteSources(1, &source);
        alDeleteBuffers(1, &buffer);
    }

    _sources = nil;
    _buffers = nil;
}

1 个答案:

答案 0 :(得分:2)

我认为你可以简单地使用Array之类的:

class FuBar {

    var sources = [ALuint](count: 2, repeatedValue: 0);
    var buffers = [ALuint](count: 2, repeatedValue: 0);

    init() {
        alGenSources(2, &sources)
        alGenBuffers(2, &buffers)
    }

    deinit {
        alDeleteSources(2, &sources)
        alDeleteBuffers(2, &buffers)
    }
}

您不必明确使用UnsafeMutablePointer,因为&的{​​{1}}的输入输出(Array)会自动转换为第一个指针数组缓冲区的元素。见the docs