How to deal with C library does malloc / free

Hello Swift community,

I have this C code in local library (.so) and make systemLibrary for it in Package.swift.

The C library does malloc / free in their functions.

How can I do what main.c does, call this C library in Swift?

Thanks

// ---- hello.h ----
#ifndef hello_h
#define hello_h

void hello_init(void **ptr, size_t size);
void hello_work(void **ptr, size_t size);
void hello_cleanup(void **ptr);

#endif
// ---- hello.c ----
#include <stdlib.h>
#include <string.h>
#include "hello.h"

void hello_init(void **mem, size_t size) {
    *mem = malloc(size);
}

void hello_work(void **mem, size_t size) {
    if (*mem) {
        char *tmp = *mem;
        memcpy(tmp, "hello world", size - 1);
        tmp[size - 1] = 0;
    }
}

void hello_cleanup(void **mem) {
    free(*mem);
    *mem = NULL;
}
// ---- main.c ----
// How to achieve this in Swift?
#include <stdio.h>
#include "hello.h"

void *memory = NULL;
const size_t MEMORY_SIZE = 1024;

int main() {
    hello_init(&memory, MEMORY_SIZE);
    hello_work(&memory, MEMORY_SIZE);
    printf("%s\n", (char*)memory);
    hello_cleanup(&memory);
}

This works for me

var memory: UnsafeMutableRawPointer? = nil
let memorySize = 1024

hello_init(&memory, memorySize)
hello_work(&memory, memorySize)
if let cString = memory?.assumingMemoryBound(to: UInt8.self) {
    print("\(String(cString: cString))")
}
hello_cleanup(&memory)
1 Like

Thank you very much.
It works for me too.

Terms of Service

Privacy Policy

Cookie Policy