Perfect CArray 简体中文
CArray is a generic class for Null-Terminated array manager with an auto release pool to help end users interact with traditional C APIs easily.
This package builds with Swift Package Manager and is part of the Perfect project. Files in this repository, however, is an independent module which can be used without specific conditions.
import PerfectCArray
// initialize a string manager
let helper = CArray<UnsafeMutablePointer<Int8>>()
// initialize a string array pointer
var array = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>(bitPattern: 0)
// append some strings to the array
let _ = helper.append(pArray: &array, element: strdup("hello"))
let _ = helper.append(pArray: &array, element: strdup("world!"))
// iterate pointers in the array, and release the strdup
helper.forEach(array: array!) { str in
let s = String(cString: str)
print(s)
free(str)
}//next
// do some more array stuff with this pointer
let total = helper.withArray(of: array!) { a -> Int in
// how many elements, including the null terminator, in the pointer?
return a.count
}//end total
print(total)
Add a dependency to Package.swift:
.Package(url: "https://github.com/PerfectSideRepos/Perfect-CArrayHelper.git", majorVersion:1)
Import Perfect-CArray to your source code:
import PerfectCArray
To manage all C fashioned arrays, e.g., a Null-Terminated string array, initialize a helper like this:
// initialize a string manager
let helper = CArray<UnsafeMutablePointer<Int8>>()
To append a new element, e.g, a string, to the end of the array pointer, especially from an empty array, please check the snippet below:
// initialize a string array pointer
var array = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>(bitPattern: 0)
// append some strings to the array
let b = helper.append(pArray: &array, element: strdup("hello"))
if b {
// the element has already been appended to the array
}else{
// something goes wrong here
}
To iterate all element in a null terminated array pointer, try the snippet below:
helper.forEach(array: array!) { element in
// check every element here
}//next
Moreover, CArray can also help you deal with the sticky C array pointer in a Swift array fashion, such as get index, set / get, and count the elements:
// do some more array stuff with this pointer
let total = helper.withArray(of: array!) { a -> Int in
// how many elements, including the null terminator, in the pointer?
return a.count
}//end total
print(total)
We are transitioning to using JIRA for all bugs and support related issues, therefore the GitHub issues has been disabled.
If you find a mistake, bug, or any other helpful suggestion you'd like to make on the docs please head over to http://jira.perfect.org:8080/servicedesk/customer/portal/1 and raise it.
A comprehensive list of open issues can be found at http://jira.perfect.org:8080/projects/ISS/issues
For more information on the Perfect project, please visit perfect.org.