3

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

That's correct, but you should deallocate the memory eventually, otherwise you have a memory leak.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.