关于String和c strcpy的快速问题 [英] a swift questions about String and c strcpy

查看:102
本文介绍了关于String和c strcpy的快速问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想快速调用c ++函数

I want to call a c++ function in swift

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));
}

所以我为此功能编写了一个对象c包装器:

So I write a object-c wrapper for this function:

-(bool) getId3Info:(const char * )filename :( const char *)artist :( const char *) title
{
    return getId3Info(filename, (char*)artist, (char*)title);
}

所以问题是我只能使用 cStringUsingEncoding

无法获得迅速的 String
$ b的真实缓冲区$ b还有另一种方法吗?

So the questions is I can only get the representation of a C string using cStringUsingEncoding ,
can not get the true buffer of a swift String,
is there another way to do this?

推荐答案

在Swift中,您可以传递 const char * 到这样的C函数:

In Swift, you can pass a const char* to a C function like this:

func foo(s: String) { s.withCString({ p in cfunction(p) }) }

或者,更明确地说,类型:

or, to be more explicit about the type:

func foo(s: String) { s.withCString({ (p:UnsafePointer<CChar>) in cfunction(p) }) }

(即p是 UnsafePointer< CChar> ,等效于 const char *

如果要从C初始化字符串函数,则需要更复杂的咒语,例如:

If you want to initialize a string from a C function, you need a more complex incantation, something like this:

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)
})

请注意,C函数必须将缓冲区保留为空终止。要么不需要修改最后一个字节(即 ptr.count-1 ,就像调用 strncpy )或者它需要添加空终止符本身(例如 snprintf ),在这种情况下,您可以传递完整的缓冲区大小。

Note that the C function must leave the buffer null-terminated. Either it needs to never modify the last byte (thus the ptr.count - 1, like you would call strncpy) or it needs to add the null terminator itself (like snprintf), in which case you can pass in the full buffer size.

这篇关于关于String和c strcpy的快速问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆