简体   繁体   English

将预分配的char *缓冲区传递给c函数

[英]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. 我在c中有一个函数接收一个预分配的字符串并用数据填充它 - 我想从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. 我发现了很多关于如何将字符串从swift传递给c的例子,但我发现没有一个显示在预分配字符串上写入数据的c函数。

The c function: c函数:

int GetData(char *dataJson, int maxSize);

On the swift side, this code compiles, but I can't find how to preallocate dataBuffer 在迅速的一面,这段代码编译,但我找不到如何预分配dataBuffer

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

Is there a way to do so in Swift? 有没有办法在Swift中这样做?

An easy way is to pass an array as inout expression with & , this calls the function with a pointer to the contiguous element storage: 一个简单的方法是使用&传递数组作为inout表达式,这将使用指向连续元素存储的指针调用该函数:

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. 优点是您不必手动管理内存,当dataBuffer超出范围时会自动释放。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM