我有一个疑问,如何将纯c
函数的返回值转换为swift。
这是我的代码:
在ViewController.swift
// swift文件
var name = getPersonName()
在personList.h
// C头文件
char getPersonName();
在personList.c
//纯C文件
#include personList.h
char getPersonName() {
char* name = "Hello, Swift";
return name;
}
这里我已经使用MyProjectName-Bridging-Header.h
通过网桥链接了personList.h文件。
由于
答案 0 :(得分:3)
如果你想让C函数返回一个字符串,那么返回类型应该是
char *
或更好const char *
:
// personList.h:
const char *getPersonName(void);
// personList.c:
const char *getPersonName(void)
{
char *name = "Hello, Swift";
return name;
}
这是作为
导入Swiftfunc getPersonName() -> UnsafePointer<Int8>
您可以使用
从返回的指针创建一个Swift字符串let name = String.fromCString(getPersonName())!
println(name) // Output: Hello, Swift
// Swift 3:
let name = String(cString: getPersonName())
print(name) // Output: Hello, Swift
&#34;万岁,&#34;你会说,&#34;这就是我需要的东西。&#34; - 但等等!!
这只是因为C函数中的"Hello, Swift"
是字符串文字。通常,您无法从中返回指向局部变量的指针
一个函数,因为指针指向的内存可能不是
从函数返回后有效。如果指针没有指向
到静态内存然后你必须复制它。例如:
const char *getPersonName(void)
{
char name[200];
snprintf(name, sizeof name, "%s %s", "Hello", "Swift!");
return strdup(name);
}
但现在调用者必须最终解除分配内存:
let cstr = getPersonName()
let name = String.fromCString(cstr)!
free(UnsafeMutablePointer(cstr))
println(name)
或者,您可以更改C函数以便调用者 传递内存而不是:
void getPersonName(char *name, size_t nameSize)
{
snprintf(name, nameSize, "%s %s", "Hello", "Swift!");
}
将从Swift中使用
var nameBuf = [Int8](count: 200, repeatedValue: 0) // Buffer for C string
getPersonName(&nameBuf, UInt(nameBuf.count))
let name = String.fromCString(nameBuf)!
println(name)
// Swift 3:
var nameBuf = [Int8](repeating: 0, count: 200) // Buffer for C string
getPersonName(&nameBuf, nameBuf.count)
let name = String(cString: nameBuf)
print(name)