Use of the C-language interface cache in swift and methods for array and string-to-pointer types

Source: Internet
Author: User

Because Swift programming language is an upper-level programming language, and Swift is due to high-performance computing interfaces for low-level, it often requires a pointer type in the C language, The swift programming language was born with the Unsafepointer and Unsafemutablepointer types, which correspond to the const type* type and type * types respectively.

In the swift programming language, it is often necessary to convert an array to a pointer type, as well as to store the contents of the elements in the array into contiguous storage space, since the generic array object cannot be used directly in the C language for function parameters that contain pointer types (for example: void*). In addition, the string objects in Swift are all string struct objects, so they also need to be converted to a type that is compatible with the const char * type in the C language, so here are some simple ways to use the pure Swift interface. Instead of relying on Objective-c's foundation library.

/** This function is used to add the value of the first element of an array (array) to 1 operations-parameters:-p:inout [Int] type, incoming array object first address-returns:void*/ func Test (inout p: [Int]) {p[0] +=1}classViewcontroller:nsviewcontroller {Override func viewdidload () { Super. Viewdidload ()varA =0                //The following uses Unsafemutablepointer's own Alloc class method to allocate storage space for 10 int elements//This method should actually be the encapsulation of the malloc function, which is useful for the external C interface .         LetBUF = unsafemutablepointer<Int>.alloc (Ten)  let DST= unsafemutablepointer<Int>.alloc (Ten)                //Initialize the BUF and DST storage spaces, respectively, by assigning values         forIinch 0.. <Ten{Buf[i]=I dst[i]=0        }                //use Assignbackwardfrom to copy the last 5 elements of the BUF storage space into the first 5 elements of the DST storage spaceDst.assignbackwardfrom (Buf.advancedby (5), Count:5)                //allocates an array object of 10 int elements with an array arr        vararr = [Int] (count:Ten, Repeatedvalue:0)                //copy all elements in DST to arr         forIinch 0.. <Ten{Arr[i]=Dst[i]} print (arr)//release buf with DST.        Note that this must be released with Dealloc, and the parameters of the inside should correspond to the alloc parameters! //do not release will cause a memory leakBuf.dealloc (Ten) Dst.dealloc (Ten)                //the arr array object points to another array literal consisting of [1, 2, 3]arr = [1,2,3]                //Call the test function so that the value of the first element of arr is added 1Test (&arr) Print ("arr = \ (arr)")                //this uses the Withunsafemutablebufferpointer method of the array to convert the contents of the Elements//point to the first address of a contiguous storage space. //so the type of P is:unsafemutablepointer<int>         Letp =Arr.withunsafemutablebufferpointer () {//here, the formal parameter is a formal parameter containing a unsafemutablebufferpointer,//returns a function type of type Unsafemutablepointer. (inoutbuffer:unsafemutablebufferpointer<Int>, unsafemutablepointer<int>inch            returnBuffer.baseaddress} A=0                //Let's first look at the contents of the elements in the original array object         forIinch 0.. <3{a+=P[i]} print ("a = \ (a)")                //we modify the contents of an array of ARR by P-pointer objectsp[0] -=1p[1] +=1p[2] +=2                //then print out the contents of the elements in the modified Arr array ObjectPrint"arr is: \ (arr)")                //here the NulTerminatedUTF8 method is first converted to the Contiguousarray<codeunit> object type,//where codeunit is the UInt8 type. //then use Withunsafebufferpointer to convert to unsafepointer<cchar> type .         LetCStr ="ABCD". Nulterminatedutf8.withunsafebufferpointer () {returnunsafepointer<CChar> ($0. baseaddress)} //The C-format string of the unsafepointer<cchar> type that you just generated is then reversed to the string object         Let string= String.fromcstring (CStr)!Print ("string is: \ (string)")    }}

In the above code, Unsafemutablepointer's Alloc method is also a good method, this method should be directly to the C language standard library malloc package, can make it easy for us to allocate continuous storage space in swift, such as for image processing, Algorithms such as matrix computing are particularly useful. Of course, if our logic is mainly handled by array, and then to the underlying C interface for high performance computing, then you can also use the array object to the continuous storage space Withunsafebufferpointer method, which is also more practical in network data communication.

Use of the C-language interface cache in swift and methods for array and string-to-pointer types

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.