Converting from Swift string to const char*

前端 未结 4 436
渐次进展
渐次进展 2020-12-03 22:54

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 artne         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 23:46

    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.

提交回复
热议问题