Examples of using Swift and C language pointers

Source: Internet
Author: User

Examples of using Swift and C language pointers

This article mainly introduces examples of using Swift and C language pointers, this article describes the parameter pointers used for input/output, the parameter pointers used as arrays, the pointer used as string parameters, and the security of pointer parameter conversion. For more information, see

Pointers are often used for Objective-C and C APIs. Both data types in Swift support pointer-based Cocoa APIs. In addition, Swift automatically processes some of the most common cases where pointers are transmitted as parameters. In this article, we will focus on making C language pointers work with variables, arrays, and strings in Swift.

#### Input/output parameter pointers

C and Objective-C do not support multiple return values. Therefore, the Cocoa API usually uses pointers as a way to transmit extra data between methods. Swift allows pointers to be used as inout parameters, so you can use the symbol & pass a reference to a variable as a pointer parameter. For example, the getRed (_: green: blue: alpha :) method in UIColor requires four CGFloat * pointers to receive the color composition information, we use & to capture the composition information as a local variable:

The Code is as follows:

Var r: CGFloat = 0, g: CGFloat = 0, B: CGFloat = 0, a: CGFloat = 0

Color. getRed (& r, green: & g, blue: & B, alpha: &)

Another common situation is the NSError usage in Cocoa. Many methods use an NSError ** parameter to store possible error information. For example, we use the contentOfDirectoryAtPath (_: error :) method of NSFileManager to list the contents in the directory and direct potential errors to a NSError? Variable:

The Code is as follows:

Var maybeError: NSError?

If let contents = NSFileManager. defaultManager ()

. ContentsOfDirectoryAtPath ("/usr/bin", error: & maybeError ){

// Work with the directory contents

} Else if let error = maybeError {

// Handle the error

}

For security, Swift requires that the variables used and passed have been initialized. It cannot be determined whether this method will try to read data from the pointer before writing data.

#### Parameter pointer used as an array

In C language, arrays and pointers are closely linked, while Swift allows arrays to be used as pointers, making it easier to work with Arrays-Based C language APIs. A fixed array can be directly transmitted using a constant pointer, and a variable array can be passed using the & operator. It is the same as the input/output parameter pointer. For example, we can use the vDSP_vadd method in the Accelerate framework to add two arrays a and B, and write the results to the third array result.

The Code is as follows:

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]

# Pointer used as a string parameter

In C, the cont char * pointer is used as the basic method for passing strings. The String in Swift can be passed to the method as a const char * pointer encoded with an infinite length UTF-8. For example, we can directly pass a string to a standard C and POSIX library method.

The Code is as follows:

Puts ("Hello from libc ")

Let fd = open ("/tmp/scratch.txt", O_WRONLY | O_CREAT, 0o666)

If fd <0 {

Perror ("cocould not open/tmp/scratch.txt ")

} Else {

Let text = "Hello World"

Write (fd, text, strlen (text ))

Close (fd)

}

# Security of pointer parameter conversion

Swift strives to make interaction with C pointers more convenient because they are widely used in Cocoa while maintaining a certain degree of security. However, compared to other Swift codes, the interaction with C pointers is potentially insecure, so be careful when using them. Note:

● If the caller saves the data of the C pointer to use it again after the returned value, the conversion is not safe to use. The converted pointer is valid only during the call. Even if you pass the same variable, array, or string as a multi-pointer parameter, you will receive a different pointer each time. This exception is stored globally or statically as a variable. You can safely use this address as a permanent and unique pointer. For example, it is used as a KVO context parameter.

● When the pointer type is Array or String, the overflow check is not mandatory. The C-language-based API cannot increase the size of arrays and strings. Therefore, before you pass them to the C-language-based API, you must ensure that the array or character size is correct.

If you do not comply with the preceding instructions when using pointer-Based APIS, Or you overwrite the Cocoa method that accepts pointer parameters, therefore, you can directly use insecure pointers in Swift to use unprocessed memory. In future articles, we will focus on more advanced situations.

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.