IOS: learning notes, Swift interaction with C pointers, and iosswift

Source: Internet
Author: User

IOS: learning notes, Swift interaction with C pointers, and iosswift
Swift and C pointer Interaction

Objective-C and C APIs often require pointers. in terms of design, Swift data types can naturally work with pointer-based Cocoa APIs. Swift automatically processes several common pointer parameters. in this article, we will see how pointer parameters in C work with variables, arrays, and strings in Swift.

Pointer as input/output parameter

C and Objective-C do not support multiple return values. Therefore, Cocoa APIs often use pointers to pass additional parameters to functions. swift allows you to regard pointer parameters as [inout] parameters, so you can use the same & syntax to pass a variable reference as a pointer. for example, the getRed (_: green: blue: alpha :) method of UIColor uses four CGFloat * pointers to accept the combination of colors. we can use & to get these values:

var r: CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0color.getRed(&r, green: &g, blue: &b, alpha: &a)

The other frequently used is NSError. many methods use the NSError * parameter to save errors. for example, we use the contentsOfDirectoryAtPath (_: error :) method of NSFileManager to list the contents in the directory and directly use NSError? Variables to save possible errors:

Var maybeError: NSError? If let contents = NSFileManager. defaultManager (). contentsOfDirectoryAtPath ("/usr/bin", error: & maybeError) {// content processing for I in contents {println (I )}} else if let error = maybeError {// error handling println (error. description )}

For security, Swift requires that the variable be initialized before use, because it does not know whether the called method will read the pointer before it is modified.

Array pointer

In C, arrays are closely linked with pointers. to facilitate the use of Array-Based C APIs, Swift allows Array as a pointer. an array that cannot be modified can be directly regarded as a constant pointer. An array that can be modified can use the & operator as a constant pointer (just like the inout parameter ). for example, we add two arrays a and B using the vDSP_vadd function (Accelerte framework) and write the results to the third array result:

  import Accelerate  let a: [Float] = [1, 2, 3, 4]  let b: [Float] = [0.5, 0.25, 0.125, 0.0625]  var result: [Float] = [0, 0, 0, 0]  vDSP_vadd(a, 1, b, 1, &result, 1, 4)  // result now contains [1.5, 2.25, 3.125, 4.0625]
String pointer

C uses the const char * pointer as the main method for passing strings. swift String can be used as the const char * pointer, which will pass the function a null end, a String pointer encoded by the UTF-8. for example, we can pass strings directly to Standard C and POSIX library functions:

  puts("Hello from libc")  let fd = open("/tmp/scratch.txt", O_WRONLY|O_CREAT, 0o666)    if fd < 0 {      perror("could not open /tmp/scratch.txt")  } else {      let text = "Hello World"      write(fd, text, strlen(text))      close(fd)  }

Security of pointer parameter conversion
Swift makes interaction with the C pointer as convenient as possible and provides certain security, because the C pointer is everywhere. however, the interaction with the C pointer is not safe than the Swift code, so pay special attention to it. special:
* These conversions cannot safely be used if the callee saves the pointer value for use after it returns. the pointer that results from these conversions is only guaranteed to be valid for the duration of a call. even if you pass the same variable, array, or string as multiple pointer arguments, you cocould receive a different pointer each time. an exception to this is global or static stored variables. you can safely use the address of a global variable as a persistent unique pointer value, e.g.: as a KVO context parameter.
* The Array and String pointers do not have a boundary check. c api will not expand the Array and String, so you need to allocate enough size for it before calling.

If the guide above does not meet your pointer interaction needs, or you want to manually control the pointer parameters, you can directly use the unsafe pointer to operate the memory. we will see more advanced applications in future articles.


I don't know how to use the C language pointer. I 'd like to learn from you.

In the past, the teacher gave an example. I modified it and now I want to share it with you...

The memory is like the locker in the supermarket. Each cabinet on the top has a serial number, which is like the memory address. The pointer is like the key to open the cabinet ....

Objective-C (Xcode, iOS, iPhone, iPad) smart pointer Problems

If you understand the memory management of Objective-C, you should understand that it refers to the reference count, which is equivalent to only pointers. Therefore, there is no need to write C ++ smart pointers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.