Brandon
Brandon

Reputation: 23525

How to get the address of swift int variable

I've done the following to allocate buffers for OpenAL in Swift:

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

And it works perfectly fine. I cannot figure out how to delete it though. I tried:

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

So how can I get the address of the source and buffer variables to pass it to the UnsafePointer<ALuint>?

I'm trying to translate my Objective-C code below to the Swift code above:

-(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;
}

Upvotes: 1

Views: 593

Answers (1)

rintaro
rintaro

Reputation: 51911

I think you can simply use Array like:

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

You don't have to use UnsafeMutablePointer explicitly, because in-out(&) expression of Array for UnsafeMutablePointer<T> is automatically converted to the pointer of the first element of the buffer of the array. see the docs.

Upvotes: 2

Related Questions