How to define typedef struct in c++ dylib in swift

Say I have an example struct in C++ that is inside dylib like this


typedef struct {
    int a;
} addingTemp;

and I need to use it for a function that adds 2 together, and store it into 3rd value


void add(addingTemp a, addingTemp b, addingTemp& c) {
    c.a = a.a + b.a;
}

how do I create the struct in swift? this is my adding library function in swift

    typealias add = @convention(c) (addingTemp, addingTemp, UnsafeMutablePointer<addingTemp>) -> Void

    func addLib(a :  addingTemp, b:  addingTemp, out: inout addingTemp) -> Void{
        guard dylib != nil  else {
            errorDylib()
            return
        }
        guard let sym = dlsym(dylib, "add")  else {
            errorDylib()
            return
        }
        
        let f = unsafeBitCast(sym, to:add.self )
        
        let result : Void = f(a ,b, &out)
     //   closeDylib()
        return
    }

this is my current implementation



public class addingTemp: NSObject {
    public var a : CInt
    init(a: CInt = 0) {
        self.a = a
    }
}

but it gives me memory access error, it looks like it isn't being stored properly as the type doesn't match.


DLL_PUBLIC void add(
        addingTemp a,
        addingTemp b,
        addingTemp* c,);

the function works when I only use Int instead of addingTemp class. Also, when the C++ function is calculating, instead of a.a = 1, b.a = 1, it outputs large numbers such as a.a = 389179664 b.a = 389179344

The only reliable way to work with [Objective-]C[++] struct values from Swift is to import the struct from a [Objective-]C header. So, put the definition of addingTemp into a .h file and import that into your Swift code and your C++ code.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How to define typedef struct in c++ dylib in swift
 
 
Q