Pass value to and from C pointers

Hello Swift commulity,

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

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

How to pass Swift argument to C pointer parameter?

And take value pointed by C pointer, back into Swift code?

Thanks.

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

struct bar_struct { double x, y; };

extern int foo;
extern struct bar_struct bar;

int add_one_foo (int *foo);

struct bar_struct add_one_bar (struct bar_struct *bar);

#endif
// ---- hello.c ----
#include "hello.h"

int foo;
struct bar_struct bar;

// add 1 to the parameter `foo`
// put back result at `both` parameter and return value
int add_one_foo (int *foo) {
    return ++*foo;
}

// with struct members
struct bar_struct add_one_bar (struct bar_struct *bar) {
    return (struct bar_struct) {++bar->x, ++bar->y};
}
// ---- main.c ----
// Test code in C. How to achieve this in Swift?
#include <stdio.h>
#include "hello.h"

int main() {
    int foo = 10;
    struct bar_struct bar = {20.0, 30.0};

    printf("before: foo: %d\n", foo);
    printf("before: bar: {%f, %f}\n", bar.x, bar.y);

    add_one_foo(&foo);
    add_one_bar(&bar);

    printf("after : foo: %d\n", foo);
    printf("after : bar: {%f, %f}\n", bar.x, bar.y);
}

This works for me

var foo: Int32 = 10
var bar = bar_struct(x: 20.0, y: 30.0)

print("before: foo: \(foo)")
print("before: bar: {\(bar.x), \(bar.y)}")

add_one_foo(&foo)
add_one_bar(&bar)

print("after: foo: \(foo)")
print("after: bar: {\(bar.x), \(bar.y)}")
1 Like

Thanks! It works for me too.

These may also interest you

1 Like