Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

c - Converting from Swift string to const char*

I'm trying to pass a const char * to an old C library converted from a Swift string in Swift.

This is the C function I'm calling:

artnet_node artnet_new(const char *ip, int verbose) { ...

how can I convert a Swift string to this const char type? It works when I pass ipAddress like this:

internal var ipAddress = "192.168.1.43"

but dit does not work when I pass it like this

internal var ipAddress:String = "192.168.1.43"

I need this in a function where I need to specify the type:

internal func setupArtnode(ip:String) -> Int{

I tried using AnyObject instead of String but that doesn't work either.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should be able to pass a String directly to a C function expecting const char * and it will be automatically converted to a null-terminated UTF-8 string:

let string = "string"
let node = artnet_new(string, 1)

See Interacting with C APIs for more information. Here is the relevant excerpt:

When a function is declared as taking an UnsafePointer argument, it can accept any of the following:

  • A String value, if Type is Int8 or UInt8. The string will automatically be converted to UTF8 in a buffer, and a pointer to that buffer is passed to the function.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...