Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create CString from NSData

Tags:

swift

nsdata

I have a C API that takes a pointer to arbitrary binary data with function signatures like the following:

void receiveData(const char *data, size_t length);

The bridging header imports this into Swift with the following definition:

func receiveData(data: CString, length: UInt)

I feel I'm missing something basic, but I can't seem to work out how to get a CString from arbitrary NSData - the only options seem to be conversion from NSString or as a string literal. How do I create the CString?

It would make more sense to be able to pass through a CConstPointer<CChar>, but the compiler isn't having a bar of it - is there some way to modify the Swift signature generated by the bridging header?

Edit: CString was removed in Xcode 6 Beta 4. From the release notes:

The CString type has been removed. Values of type const char * are now imported as ConstUnsafePointer instead of CString. C macros that expand to string literals are imported as String.

like image 426
Sam Avatar asked Aug 29 '26 15:08

Sam


1 Answers

A C string is null-terminated. Arbitrary binary data doesn't need to be null terminated. I think the problem is that the bridging mechanism sees a char * and thinks "C string". Perhaps if you changed it to void *, you will get a more appropriate type in Swift.

like image 159
newacct Avatar answered Sep 01 '26 08:09

newacct



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!