Saturday, October 14, 2023
HomeiOS DevelopmentTips on how to use C libraries in Swift?

Tips on how to use C libraries in Swift?


Constructing a customized C library utilizing SPM


You should utilize the Swift Bundle Supervisor to create C household based mostly supply recordsdata (C, C++, Goal-C and Goal-C++) and ship them as standalone elements. If you do not know a lot in regards to the Swift Bundle Supervisor, it’s best to learn my complete tutorial about how SPM works. 📦


The one factor that you should setup a library is a typical Bundle.swift manifest file with a barely altered listing construction to help header recordsdata. Let’s make a MyPoint library.



import PackageDescription

let package deal = Bundle(
    identify: "MyPoint",
    merchandise: [
        .library(name: "MyPoint", targets: ["MyPoint"]),
    ],
    targets: [
        .target(name: "MyPoint"),
    ]
)


The whole lot that you simply put into the header file might be publicly out there for different builders to make use of, the implementation particulars are going to be situated instantly below the Sources/[target]/ listing, however it’s a must to create an extra embrace folder on your headers. Let’s make a MyPoint.h file below the Sources/MyPoint/embrace path with the next contents.

struct MyPoint {
   int x;
   int y;
};

We have simply outlined the general public interface for our library. Now should you attempt to compile it by the swift construct command, it’s going to complain that the venture is lacking some supply recordsdata. We are able to simply repair this by creating an empty MyPoint.c file below the Sources/MyPoint listing.


While you import an area header file to make use of in your implementation code, you possibly can skip the “embrace” path and easily write #embrace "MyPoint.h". You could possibly additionally put every kind of C household elements into this venture, this technique works with C++, Goal-C and even Goal-C++ recordsdata.


You could possibly additionally place header recordsdata subsequent to the implementation supply code, however in that case the system will not be capable to auto-locate your public (umbrella) header recordsdata, so that you additionally need to create a modulemap file and supply the right location of your headers explicitly. When you use the construction with the embrace listing SPM will generate the whole lot for you routinely.


Congratulations, you simply shipped your first C code with Swift Bundle Supervisor. 🥳



Interacting with C libraries utilizing Swift



We will create a model new Swift package deal to construct an executable utility based mostly on the beforehand created C library. To be able to use an area package deal you possibly can merely specify it as with the trail argument below the dependencies in your Bundle.swift manifest file.



import PackageDescription

let package deal = Bundle(
    identify: "Pattern",
    merchandise: [
        .executable(name: "Sample", targets: ["Sample"]),
    ],
    dependencies: [
        .package(path: "../MyPoint")
    ],
    targets: [
        .target(name: "Sample", dependencies: [
            .product(name: "MyPoint", package: "MyPoint"),
        ]),
    ]
)


This time we’re going to use the MyPoint library as an area dependency, however after all you possibly can handle and publish your personal libraries utilizing a git repository someplace within the cloud. Subsequent we should always create our Sources/Pattern/essential.swift file, import the library and write some code.


import MyPoint

let p = MyPoint(x: 4, y: 20)
print("Hi there, world!", p.x, p.y)


If each packages can be found regionally, be sure to place them subsequent to one another, then the whole lot ought to work like a appeal. You may open the Pattern venture manifest file utilizing Xcode as nicely, the IDE can resolve package deal dependencies routinely for you, however should you desire the command line, you should use the swift run command to compile & run the executable goal.


With this method you possibly can import the MyPoint module from another Swift package deal and use the out there public elements from it. You simply have so as to add this module as a dependency, by the best way you possibly can even name this module from one other C (C++, ObjC, Objc++) venture made with SPM. 😎


Tips on how to use C system libraries from Swift?


There are millions of out there instruments that you may set up in your working system (Linux, macOS) with a package deal supervisor (apt, brew). For instance there may be the well-known curl command line instrument and library, that can be utilized for transferring information from or to a server. In different phrases, you can also make HTTP requests with it, simply sort curl "https://www.apple.com/" right into a terminal window.


These system elements are often constructed round libraries. In our case curl comes with libcurl, the multiprotocol file switch library. Generally you would possibly need to use these low stage elements (often written in C) in your utility, however how can we add them as a dependency? 🤔


The reply is straightforward, we will outline a brand new systemLibrary goal in our package deal manifest file.



import PackageDescription

let package deal = Bundle(
    identify: "Pattern",
    merchandise: [
        .executable(name: "Sample", targets: ["Sample"]),
    ],
    dependencies: [
        .package(path: "../MyPoint")
    ],
    targets: [

        .systemLibrary(
            name: "libcurl",
            providers: [
                .apt(["libcurl4-openssl-dev"]),
                .brew(["curl"])
            ]
        ),

        .goal(identify: "Pattern", dependencies: [
            .product(name: "MyPoint", package: "MyPoint"),
            .target(name: "libcurl"),
        ]),
    ]
)


Contained in the Bundle.swift file you possibly can set the suppliers for the library (corresponding to brew for macOS or aptitude for a lot of Linux distributions). Sadly you continue to need to manually set up these packages, as a result of SPM will not do that for you, consider it as “only a reminder” for now… 😅


It will permit us to create a customized modulemap file with extra headers (common or umbrella) and linker flags inside our venture folder. First, we should always add the next modulemap definition to the Sources/libcurl/module.modulemap file. Please create the libcurl listing, if wanted.


module libcurl [system] {
    header "libcurl.h"
    hyperlink "curl"
    export *
}


The idea of modules are coming from (clang) LLVM, I extremely advocate checking the linked article if you wish to know extra about modulemaps. This fashion we inform the compiler that we need to construct a module based mostly on the curl library, therefore we hyperlink curl. We additionally need to present our customized header file to make some extra stuff out there or extra handy. Folks often name these header recordsdata shims, umbrella headers or bridging headers.


An umberlla header is the primary header file for a framework or library. A bridging header permits us to make use of two languages in the identical utility. The shim header works across the limitation that module maps should include absolute or native paths. All of them exposes APIs from a library or language to a different, they’re very comparable, however they don’t seem to be the identical idea. 🙄


In our case we’ll create a libcurl.h header file contained in the Sources/libcurl folder. The module map merely refers to this header file. Here is what we’ll place within it.





typedef size_t (*curl_func)(void * ptr, size_t dimension, size_t num, void * ud);

CURLcode curl_easy_setopt_string(CURL *curl, CURLoption possibility, const char *param) {
    return curl_easy_setopt(curl, possibility, param);
}

CURLcode curl_easy_setopt_func(CURL *deal with, CURLoption possibility, curl_func param) {
    return curl_easy_setopt(deal with, possibility, param);
}

CURLcode curl_easy_setopt_pointer(CURL *deal with, CURLoption possibility, void* param) {
    return curl_easy_setopt(deal with, possibility, param);
}


This code comes from the archived SoTS/CCurl repository, however should you test the shim file contained in the Kitura/CCurl package deal, you may discover a just about comparable strategy with much more handy helpers.

The principle cause why we’d like these features is that variadic features cannot be imported by Swift (but), so we’ve got to wrap the curl_easy_setopt calls, so we’ll be capable to use it from Swift.

Okay, let me present you the way to write a low-level curl name utilizing the libcurl & Swift.


import Basis
import MyPoint
import libcurl

class Response {
    var information = Information()

    var physique: String { String(information: information, encoding: .ascii)! }
}

var response = Response()

let deal with = curl_easy_init()
curl_easy_setopt_string(deal with, CURLOPT_URL, "http://www.google.com")

let pointerResult = curl_easy_setopt_pointer(deal with, CURLOPT_WRITEDATA, &response)
guard pointerResult == CURLE_OK else {
    fatalError("Couldn't set response pointer")
}
curl_easy_setopt_func(deal with, CURLOPT_WRITEFUNCTION) { buffer, dimension, n, reference in
    let size = dimension * n
    let information = buffer!.assumingMemoryBound(to: UInt8.self)
    let p = reference?.assumingMemoryBound(to: Response.self).pointee
    p?.information.append(information, depend: size)
    return size
}

let ret = curl_easy_perform(deal with)
guard ret == CURLE_OK else {

    fatalError("One thing went flawed with the request")
}
curl_easy_cleanup(deal with)

print(response.physique)


I do know, I do know. This seems to be horrible for the primary sight, however sadly C interoperability is all about coping with pointers, unfamiliar sorts and reminiscence addresses. Anyway, this is what occurs within the code snippet. First we’ve got to outline a response object that may maintain the information coming from the server as a response. Subsequent we name the system funtions from the curl library to create a deal with and set the choices on it. We merely present the request URL as a string, we move the end result pointer and a write operate that may append the incoming information to the storage when one thing arrives from the server. Lastly we carry out the request, test for errors and cleanup the deal with.


It isn’t so dangerous, however nonetheless it seems to be nothing such as you’d count on from Swift. It is only a primary instance I hope it’s going to allow you to to grasp what is going on on below the hood and the way low stage C-like APIs can work in Swift. If you wish to observe it’s best to strive to check out the Kanna library and parse the response utilizing a customized libxml2 wrapper (or you possibly can examine a SQLite3 wrapper). 🤓


The system library goal function is a pleasant method of wrapping C [system] modules with SPM. You may learn extra about it on the official Swift boards. In case you are nonetheless utilizing the previous system library package deal sort format, please migrate, because it’s deprecated and it will be utterly eliminated afterward.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments