C and Swift – strcpy

Below are some of the things I’ve needed to do recently, when interfacing with C code. Maybe these will be useful to someone. I’m trying to implement Unix-domain sockets in Swift, and it’s been kind of painful. Dealing with sockaddr_un and Tuples of Int8, these are not fun things.

Anyhow, copied from a playground:

var str = "Hello, World"

let dst = UnsafeMutablePointer.alloc(20)

strcpy(dst, str)

let ss = String.fromCString(dst)

print("\(ss)")						// "Hello, World"

var fname = sockaddr_un()

let l = strideof(sockaddr_un)				// 106

let ll = sizeof(sockaddr_un)				// 106

withUnsafeMutablePointer(&fname.sun_path) { strcpy(UnsafeMutablePointer($0), 
						"Foobar") }

var ns = "Some.path.name"

// Here's the complete initialization of a sockaddr_un. I tried hard to figure out
// how to initialize all the fields at once but the tuple sun_path presented a
// larger challenge than I could surmount.
var fname2 = sockaddr_un()
fname2.sun_family = UInt8(AF_LOCAL)
// SUN_PATH is a macro that you can't use from Swift. 
// Supposedly you can just use the whole size. I haven't
// tested this yet.
fname2.sun_len = UInt8(sizeof(sockaddr_un))

ns.withCString { path in
	withUnsafeMutablePointer(&fname.sun_path) { sun_path in
		strcpy(UnsafeMutablePointer(sun_path), path)

That’s all for now…

Leave a Reply

Your email address will not be published. Required fields are marked *