ios - How to get return values from pure C function to swift? -
I have a doubt, how to get the fast return value from the pure c function.
My code here: ViewController.swift // Quick file
var name = getPersonName ()personList.h// C header file in pre>
char getPersonName ();.In the
personList.c// Pure C file#include personList.h char getPersonName () {char * name = "Hello, Swift"; Name of return; }Already I am MyProjectName-Bridging-Header.h
Thanks
by linking the personList.h file.
If you want the C function to return a string, the return type should be char * or better const char * :
// personList.h: const char * getPersonName (zero); // personList.c: const char * getPersonName (zero) {char * name = "hello, swift"; Name of return; } It is imported as SWIF
func getPersonName () -> UnsafePointer & LT; Int8 & gt; and you can create a swift string from the returned indicators
name = string.frame severing (getPersonName ())! Println (name) // output: hello, swift // swift 3: name = string (cString: getPersonName ()) print (name) // output: hello, swift " Hurray, "you will say," I want it. "- But wait !! It works only because is "hello, swift" normally you can call a pointer from a function Can not return to the variable, because it indicates memory that the pointer can not be validated after returning from the function. If the indicator does not point to static memory then you will have to duplicate example:
const char * getPersonName (zero) {letter name [200]; Snprintf (name, shape name, "% s% s", "hello", "swift!"); Return stdup (name); } But now the caller must do deallocate memory at the end:
let cstr = getPersonName () name = string .fromCString (CSTR)! Alternatively, you can change the C function so that the caller can pass the memory instead: zero GetPersonName (char * name, size_t nameSize) {snprintf (name, name size, "% S% s "," hello "," swift! "); }
will be used by SWIFT
var nameBuf = [Int8] (gin: 200, repeated value: 0) // buffer C string Name GetPersonName (& amp; nameBuf, UInt (nameBufCount)) = String.First C string (nameBuf)! Println (name) // swift 3: var nameBuf = [Int8] (repeat: 0, count: 200) // string for get buffer getPersonName (& amp; nameBuf, nameBuf.count) name = string (cString: nameBuf) Print (name)
Comments
Post a Comment