简体   繁体   English

C结构转换为Swift

[英]C Struct to Swift

in c file : have a struct 在c文件中:有一个结构

struct CPerson {
  const char* name;
  int age;
};

in swift file: 在快速文件中:

extension UnsafePointer where Pointee == Int8 {
  var string : String? {
     return String.init(cString: self)
  }
}

I try use c struct: 我尝试使用c struct:

print(CPerson(name: "baby", age: 1).name.string)
//Optional("baby")

but : 但是:

let p = CPerson(name: "angela", age: 1)
print(p.name.string , p.age)
//Optional("") 1

why p.name.string == "" ? 为什么p.name.string ==“”?

I hope that p.name.string == "angela" 我希望p.name.string ==“ angela”

thanks. 谢谢。

It is a memory management problem. 这是一个内存管理问题。 In

 let p = CPerson(name: "angela", age: 1)

you pass a Swift String to a function taking an UnsafePointer<Int8> argument (the Swift equivalent of const char * ). 您将Swift String传递给带有UnsafePointer<Int8>参数的函数(与const char *的Swift等效)。 The compiler inserts code to create a temporary C string representation and passes that to the CPerson initializer. 编译器插入代码以创建一个临时 C字符串表示形式,并将其传递给CPerson初始化程序。 The name field then points to that temporary C string. 然后, name字段指向该临时C字符串。

The problem is that this pointer is no longer valid when the initializer returns. 问题是初始化初始化器返回时,该指针不再有效。 It may point to something else or may be an invalid pointer. 它可能指向其他内容,或者可能是无效的指针。

A const char * in C is just a pointer, it does not imply any ownership or memory management. C语言中的const char *只是一个指针,并不意味着任何所有权或内存管理。 You would have exactly the same problem in C if you assign 如果分配,您在C中会遇到完全相同的问题

person.name = someString;

and leave the scope where someString is defined. 并保留定义了someString的范围。

So you have to decide who is responsible to allocate (and free) the C string storage. 因此,您必须确定谁负责分配(和释放)C字符串存储。

One option would be to duplicate the string in Swift and release the memory when it is no longer needed: 一种选择是在Swift中复制字符串并在不再需要时释放内存:

let name = strdup("angela")

let p = CPerson.init(name: name, age: 1)
print(p.name.string , p.age) // Optional("angela") 1

free(name)

Another option might be to create C functions CreatePerson() and ReleasePerson() which allocate and release the storage. 另一个选择可能是创建分配和释放存储的C函数CreatePerson()ReleasePerson()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM