Nitay
Nitay

Reputation: 4720

Passing a preallocated char* buffer to a c function

I have a function in c that receives a preallocated string and fills it with data - I'd like to call this function from swift. I've found many examples on how to pass strings from swift to c, but I found none showing c functions that write the data on a preallocated string.

The c function:

int GetData(char *dataJson, int maxSize);

On the swift side, this code compiles, but I can't find how to preallocate dataBuffer

let dataBuffer = UnsafePointer<UInt8>
GetData(dataBuffer, 2048)

Is there a way to do so in Swift?

Upvotes: 3

Views: 698

Answers (2)

Martin R
Martin R

Reputation: 540105

An easy way is to pass an array as inout expression with &, this calls the function with a pointer to the contiguous element storage:

var dataBuffer = Array<Int8>(repeating: 0, count: 2048)
let result = GetData(&dataBuffer, numericCast(dataBuffer.count))

The advantage is that you don't have to manage the memory manually, it is released automatically when dataBuffer goes out of scope.

Upvotes: 7

Nitay
Nitay

Reputation: 4720

I've figured it out, here's the code for future reference:

let dataBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: 2048)
GetData(dataBuffer, 2048)
let jsonData = String(cString: dataBuffer)

Upvotes: 0

Related Questions