puru020
puru020

Reputation: 818

Setting char[] inside c struct from swift

The char[10] inside a C struct is imported as tuple of 10 UInt8 items. There's a lot of examples on how to read values as swift string from that struct member, but I want to be able to set something in member?

struct CStrut {
char[10] item;
}

How can set value in item from swift?

Upvotes: 0

Views: 115

Answers (2)

MaddTheSane
MaddTheSane

Reputation: 3031

One way is to use withUnsafeMutablePointer(_:_:):

var a = CStruct(item: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
var CStructPtr = withUnsafeMutablePointer(&a.item) { (b) -> UnsafeMutableBufferPointer<Int8> in
    // UnsafeMutableBufferPointer is used because it a little more safe.
    return UnsafeMutableBufferPointer(start: UnsafeMutablePointer<Int8>(b), count: 10)
}

//Modify the tuple however you want
CStructPtr[0] = 42
CStructPtr[1] = 30

Upvotes: 0

Code Different
Code Different

Reputation: 93161

You got a syntax error in C:

struct CStruct {
    char item[10];
};

If you want to modify it in Swift:

var a = CStruct(item: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
a.item.0 = 42
a.item.1 = 30

print(a)

Upvotes: 0

Related Questions