Ios 关于字符串和c strcpy的快速提问

Ios 关于字符串和c strcpy的快速提问,ios,string,swift,cstring,Ios,String,Swift,Cstring,我想在swift中调用一个c++函数 bool getId3Info(const char * filename , char *artist , char * title ) { // get the file's id3v2 tag, write info back strcpy(artist,(const char*) id3v2tag->artist().toCString(true)); strcpy(title,id3v2tag->title(

我想在swift中调用一个c++函数

bool getId3Info(const char * filename , char *artist , char * title  )
{
     // get the file's id3v2 tag, write info back
    strcpy(artist,(const char*) id3v2tag->artist().toCString(true));
    strcpy(title,id3v2tag->title().toCString(true));
}
因此,我为这个函数编写了一个object-c包装器:

-(bool) getId3Info:(const char * )filename :( const char *)artist :( const char *) title
{
    return getId3Info(filename, (char*)artist, (char*)title);
}
所以问题是我只能用
cstringusingencode

无法获取swift
字符串的真实缓冲区,

还有其他方法吗?

在Swift中,您可以将
const char*
传递给C函数,如下所示:

func foo(s: String) { s.withCString({ p in cfunction(p) }) }
var buf = Array<CChar>(count: 1000, repeatedValue: 0);
let result = buf.withUnsafeMutableBufferPointer({
        (inout ptr: UnsafeMutableBufferPointer<CChar>) -> String? in
    cfunction(ptr.baseAddress, ptr.count - 1)
    String.fromCString(ptr.baseAddress)
})
或者,要更明确地说明类型:

func foo(s: String) { s.withCString({ (p:UnsafePointer<CChar>) in cfunction(p) }) }
注意,C函数必须使缓冲区null终止。要么它永远不需要修改最后一个字节(因此
ptr.count-1
,就像您调用
strncpy
),要么它需要添加空终止符本身(比如
snprintf
),在这种情况下,您可以传递完整的缓冲区大小