0

I want to implement C library into my iOS project. I'm using swift language.

I have a function where the input parameter - where output values are stored - is ar usual C double array:

double ar[6];
///...
 err = c_lib_func(ar);

If I initialize inside swift like var ar: [Double] xCode says I have to use

UnsafeMutablePointer. But inside the docs I haven't found how to initialize n-lenght array for UnsafeMutablePointer. I just can do something like this: var ar : UnsafeMutablePointer<Double>. But I can understand how to initialize it as 6-length array. Please, help me.

If I'm using

ar = [Double]
err = c_lib_func(ar);

the xCode shows to me this error:

/Users/admin/Documents/projects/myApp/myApp/file.swift:46:46: Cannot convert value of type '[Double]' to expected argument type 'UnsafeMutablePointer'

7
  • With var ar: [Double] you should be able to call c_lib_func(ar). Commented Mar 28, 2016 at 6:02
  • @jtbandes , no. xCode show the error about using UnsafeMutablePointer Commented Mar 28, 2016 at 6:03
  • Please show your code and the error: How to Ask Commented Mar 28, 2016 at 6:04
  • Someone wants to close this question? lol Commented Mar 28, 2016 at 6:11
  • Does using &ar to reference the underlying UnsafeMutablePointer work when ar is of type [Double]? Commented Mar 28, 2016 at 6:11

1 Answer 1

1

In Swift, [Double] is an array of double values which is not what you are after. If you want to initialize an UnsafeMutablePointer you can just use:

var ar = UnsafeMutablePointer<Double>.alloc(6)

Use ar.dealloc(6) to release the memory again.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it important to use dealloc inside swift?
Yes and it's also important that the value matches the value passed to alloc().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.