[swift-users] How to get UnsafePointer or UnsafeMutablePointer from ContiguousArray?

Dmitri Gribenko gribozavr at gmail.com
Thu Feb 11 02:38:18 CST 2016


On Thu, Feb 11, 2016 at 12:19 AM, Dmitri Gribenko <gribozavr at gmail.com> wrote:
> On Thu, Feb 11, 2016 at 12:13 AM, Sergey Kuratov <ksubox.swift at gmail.com> wrote:
>>>> Can I define similar for my Swift classes ?
>>
>>>No.  What would be your use case?
>>
>> I also could have my Swift object with several members, but when send to
>> native part would like to send address exactly one of members.
>> Something like this:
>>
>> // Swift part
>>
>> class ABlock {
>>
>> var channels = 2
>>
>> var samplerate = 44100
>>
>> var  buffer : UnsafeMutablePointer<Int16>
>>
>> init() {
>>
>> buffer = UnsafeMutablePointer<Int16>.alloc(2048)
>>
>> }
>>
>> deinit {
>>
>> buffer.dealloc(2048)
>>
>> }
>>
>> }
>>
>>
>> var block = ABlock
>> generate(block) <- here I would like to send address of ABlock.buffer to
>> native part
>>
>> // C part
>> void generate(int16_t *buf) {
>> ...
>> }
>
> I'd recommend to write a Swift wrapper for your C code that accepts
> the class instance, and calls the generate() function with appropriate
> arguments.

Oh, and since your class stores an unsafe pointer (and not an array),
you'd need to call _fixLifetime() on it after the your C function
returns, to ensure that the class instance can't be deallocated before
then.  Unless you have other requirements though, I'd recommend just
storing an array though.  Then you wouldn't need to care about
_fixLifetime().

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-users mailing list