Swift use c struct

后端 未结 3 976
孤城傲影
孤城傲影 2021-02-01 08:31

Sorry for the title, I can\'t find words to describe my question in few words.

I already know that swift can use struct written in c. For example

In Bridging-Hea

3条回答
  •  无人共我
    2021-02-01 09:14

    Bridging-Header.h

    #include "user_input.h"
    

    user_input.c

    #include 
    
    struct Pointer {
        int x;
        int y;
    };
    
    Pointer *create_pointer() {
        Pointer *p = malloc(sizeof(struct Pointer));
        if (p) {
            p->x = 20;
            p->y = 20;
        }
        return p;
    }
    
    void delete_pointer(Pointer *p) {
        free(p);
    }
    
    int pointer_x(Pointer *p) {
        return p->x;
    }
    
    int pointer_y(Pointer *p) {
        return p->y;
    }
    

    user_input.h

    #ifndef __user_input_h__
    #define __user_input_h__
    
    typedef struct Pointer Pointer;
    Pointer *create_pointer();
    void delete_pointer(Pointer *p);
    int pointer_x(Pointer *p);
    int pointer_y(Pointer *p);
    
    #endif
    

    main.swift

    import Foundation
    
    var pointer: COpaquePointer = create_pointer()
    println("\(pointer_x(pointer)), \(pointer_y(pointer))")
    delete_pointer(pointer)
    
    // Writing the wrapper class could be helpful.
    
    class CPointer {
        var _ptr: COpaquePointer
    
        init() {
            _ptr = create_pointer()
            assert(_ptr, "Failed on create_pointer()")
        }
    
        deinit {
            delete_pointer(_ptr)
        }
    
        var x: Int {
            get { return Int(pointer_x(_ptr)) }
        }
    
        var y: Int {
            get { return Int(pointer_y(_ptr)) }
        }
    }
    
    var p = CPointer()
    println("\(p.x), \(p.y)")
    

提交回复
热议问题