I wants to pass structure to the c function .
I have 3 files .
- lib.dylib -> file contains function definition
- lib.h -> file contains function declaration
- structdefination.h -> file contains structure declaration
I am using Xcode for creating project . After creating project when i have add two file to the project i.e lib.dylib and lib.h .
function declaration for c function in lib.h file was like
extern Info create(Ref p0, char* p1, Config* p2, char** p3);
After clicking on Generated Interface in Xcode for lib.h . Function declaration for same function is
public func create(_ p0: Int32, _ p1: UnsafeMutablePointer<Int8>!, _ p2: UnsafeMutablePointer<Int32>!, _ p3: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>!) -> Int32
When i add third file ( i.e structdefination.h) to the project . After adding the file when i click on Generated interface . Function declaration for same function changes . may due to including structure declaration file in project .
New function declaration:
public func create(_ p0: Ref, _ p1: UnsafeMutablePointer<Int8>!, _ p2: UnsafeMutablePointer<Config>!, _ p3: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>!) -> Info
Type alias created for c function :
typealias create = @convention(c)(Int32,UnsafeMutablePointer<Int8>?,UnsafeMutableRawPointer?,UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?)-> -> Int32
Swift code using for calling c function :
let dynammicFileHandle = dlopen("lib.dylib",RTLD_LOCAL|RTLD_NOW)
if(dynammicFileHandle != nil){
let sym = dlsym(dynammicFileHandle, "create")
if(sym != nil){
let create = unsafeBitCast(sym, to: create.self)
let error : NSString = ""
var ptrToerror = UnsafeMutablePointer<CChar>(mutating: error.utf8String)
let ptrToName = UnsafeMutablePointer<CChar>(mutating: Name.utf8String)
var config = Config()// How can i create c structure in swift
let ptrConfig = UnsafeMutableRawPointer(&config)
//let Result = create(Ref,ptrTotName, ptrToConfig , &ptrToerror)//How can i pass structure
}else{
print("Handle not found ")
}
Tired :
I have tried to define c structure in swift and create typealias as ((structure ,Data)->(structurename))
But when program executes shows error
Can't unsafeBitCast between types of different sizes
Question
- How can i declare c structure in swift and pass same structure pointer to the c function using swift 5 ?
Note : I am creating SPM Package