Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift.String to CMutablePointer<CChar>

Tags:

c

swift

I've imported and created a bridging header for some old C source code to Swift. The function signature looks like so:

struct Message prattle_parse_message(char *line);

The swift declaration for it is:

func prattle_parse_message(line: CMutablePointer<CChar>) -> Message

However, I'm not sure how to convert a Swift String (or an NSString) to a CMutablePointer<CChar> to be passed to this function.

("Test" as NSString).UTF8String returns a CString which won't work.

Could someone point me in the right direction with this?

like image 956
Fionn Kelleher Avatar asked Jun 10 '26 09:06

Fionn Kelleher


1 Answers

This should be it...

var data =     inString.dataUsingEncoding(encoding, allowsLossyConversion: allow)
var ccharstr = CChar[](count:data.length, repeatedValue:CChar(0))  

data.getBytes(&ccharstr length:data.length)

ccharstr.append(CChar(0))

var message =  prattle_parse_message(&ccharstr)

Can't test the last line but I think this should work

like image 147
iluvcapra Avatar answered Jun 13 '26 02:06

iluvcapra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!