Converting Objective-C memcpy to Swift










3














I am tasked with converting some functions from Objective-C to Swift. We are using a C file to transfer files to a bluetooth device. Here is the Objective-C code that needs to be converted.



From the Objective-C file:



NSString *room_name = filename;
NSData* bytes = [room_name dataUsingEncoding:NSUTF8StringEncoding];
UInt8 buff_name[bytes.length+1];
memcpy(buff_name, [room_name UTF8String],[room_name lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);


I am stuck on memcpy for Swift and am not sure this is the safest method for what we are trying to do. Thank you.










share|improve this question



















  • 1




    There's probably more code here than the question needs. For clarity for future people who find this question via a search, can you remove the parts unrelated to the memcpy issue?
    – Charles Srstka
    Nov 9 at 22:23










  • @CharlesSrstka updated.
    – temp_
    Nov 9 at 22:26















3














I am tasked with converting some functions from Objective-C to Swift. We are using a C file to transfer files to a bluetooth device. Here is the Objective-C code that needs to be converted.



From the Objective-C file:



NSString *room_name = filename;
NSData* bytes = [room_name dataUsingEncoding:NSUTF8StringEncoding];
UInt8 buff_name[bytes.length+1];
memcpy(buff_name, [room_name UTF8String],[room_name lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);


I am stuck on memcpy for Swift and am not sure this is the safest method for what we are trying to do. Thank you.










share|improve this question



















  • 1




    There's probably more code here than the question needs. For clarity for future people who find this question via a search, can you remove the parts unrelated to the memcpy issue?
    – Charles Srstka
    Nov 9 at 22:23










  • @CharlesSrstka updated.
    – temp_
    Nov 9 at 22:26













3












3








3







I am tasked with converting some functions from Objective-C to Swift. We are using a C file to transfer files to a bluetooth device. Here is the Objective-C code that needs to be converted.



From the Objective-C file:



NSString *room_name = filename;
NSData* bytes = [room_name dataUsingEncoding:NSUTF8StringEncoding];
UInt8 buff_name[bytes.length+1];
memcpy(buff_name, [room_name UTF8String],[room_name lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);


I am stuck on memcpy for Swift and am not sure this is the safest method for what we are trying to do. Thank you.










share|improve this question















I am tasked with converting some functions from Objective-C to Swift. We are using a C file to transfer files to a bluetooth device. Here is the Objective-C code that needs to be converted.



From the Objective-C file:



NSString *room_name = filename;
NSData* bytes = [room_name dataUsingEncoding:NSUTF8StringEncoding];
UInt8 buff_name[bytes.length+1];
memcpy(buff_name, [room_name UTF8String],[room_name lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);


I am stuck on memcpy for Swift and am not sure this is the safest method for what we are trying to do. Thank you.







objective-c swift swift-converter






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









Md. Ibrahim Hassan

3,47111030




3,47111030










asked Nov 9 at 22:21









temp_

229413




229413







  • 1




    There's probably more code here than the question needs. For clarity for future people who find this question via a search, can you remove the parts unrelated to the memcpy issue?
    – Charles Srstka
    Nov 9 at 22:23










  • @CharlesSrstka updated.
    – temp_
    Nov 9 at 22:26












  • 1




    There's probably more code here than the question needs. For clarity for future people who find this question via a search, can you remove the parts unrelated to the memcpy issue?
    – Charles Srstka
    Nov 9 at 22:23










  • @CharlesSrstka updated.
    – temp_
    Nov 9 at 22:26







1




1




There's probably more code here than the question needs. For clarity for future people who find this question via a search, can you remove the parts unrelated to the memcpy issue?
– Charles Srstka
Nov 9 at 22:23




There's probably more code here than the question needs. For clarity for future people who find this question via a search, can you remove the parts unrelated to the memcpy issue?
– Charles Srstka
Nov 9 at 22:23












@CharlesSrstka updated.
– temp_
Nov 9 at 22:26




@CharlesSrstka updated.
– temp_
Nov 9 at 22:26












1 Answer
1






active

oldest

votes


















3














My condolences, as the code you were given is a bit of a mess. First, it makes an NSData from room_name, converting the string to UTF-8 in the process, but then it doesn't use that NSData for anything other than to determine the size of a buffer, and then it converts the string to UTF-8 again and copies it into the new buffer. This is a lot more inefficient, both from a computational and a readability standpoint, than it needs to be.



If we were leaving this in Objective-C, we'd already want to clean up the code. However, in Swift, we can make this even cleaner, because String has a really nice and simple method to get us a pointer to the string's UTF-8 representation:



filename.withCString ptr in
// call whatever C-based functions expect a `const char *` pointer here



Note that the pointer you get here is immutable. If the C functions you're calling expect to be able to modify the buffer, you'll want to make a copy instead. There are a few ways to do this, but the easiest is probably just to:



guard var data = filename.data(using: .utf8) else 
// handle this error somehow


data.withUnsafeMutableBytes (ptr: UnsafeMutablePointer<Int8>) in
// call whatever C-based functions expect a `char *` pointer here
// (if you need `unsigned char *`, use `UInt8` instead of `Int8`)






share|improve this answer






















  • To make things worse, all of the comments are in Chinese.
    – temp_
    Nov 9 at 22:47






  • 1




    @temp_ Hang in there. Taking a kitten-video break every so often may help preserve your sanity.
    – Charles Srstka
    Nov 9 at 22:49











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234022%2fconverting-objective-c-memcpy-to-swift%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














My condolences, as the code you were given is a bit of a mess. First, it makes an NSData from room_name, converting the string to UTF-8 in the process, but then it doesn't use that NSData for anything other than to determine the size of a buffer, and then it converts the string to UTF-8 again and copies it into the new buffer. This is a lot more inefficient, both from a computational and a readability standpoint, than it needs to be.



If we were leaving this in Objective-C, we'd already want to clean up the code. However, in Swift, we can make this even cleaner, because String has a really nice and simple method to get us a pointer to the string's UTF-8 representation:



filename.withCString ptr in
// call whatever C-based functions expect a `const char *` pointer here



Note that the pointer you get here is immutable. If the C functions you're calling expect to be able to modify the buffer, you'll want to make a copy instead. There are a few ways to do this, but the easiest is probably just to:



guard var data = filename.data(using: .utf8) else 
// handle this error somehow


data.withUnsafeMutableBytes (ptr: UnsafeMutablePointer<Int8>) in
// call whatever C-based functions expect a `char *` pointer here
// (if you need `unsigned char *`, use `UInt8` instead of `Int8`)






share|improve this answer






















  • To make things worse, all of the comments are in Chinese.
    – temp_
    Nov 9 at 22:47






  • 1




    @temp_ Hang in there. Taking a kitten-video break every so often may help preserve your sanity.
    – Charles Srstka
    Nov 9 at 22:49
















3














My condolences, as the code you were given is a bit of a mess. First, it makes an NSData from room_name, converting the string to UTF-8 in the process, but then it doesn't use that NSData for anything other than to determine the size of a buffer, and then it converts the string to UTF-8 again and copies it into the new buffer. This is a lot more inefficient, both from a computational and a readability standpoint, than it needs to be.



If we were leaving this in Objective-C, we'd already want to clean up the code. However, in Swift, we can make this even cleaner, because String has a really nice and simple method to get us a pointer to the string's UTF-8 representation:



filename.withCString ptr in
// call whatever C-based functions expect a `const char *` pointer here



Note that the pointer you get here is immutable. If the C functions you're calling expect to be able to modify the buffer, you'll want to make a copy instead. There are a few ways to do this, but the easiest is probably just to:



guard var data = filename.data(using: .utf8) else 
// handle this error somehow


data.withUnsafeMutableBytes (ptr: UnsafeMutablePointer<Int8>) in
// call whatever C-based functions expect a `char *` pointer here
// (if you need `unsigned char *`, use `UInt8` instead of `Int8`)






share|improve this answer






















  • To make things worse, all of the comments are in Chinese.
    – temp_
    Nov 9 at 22:47






  • 1




    @temp_ Hang in there. Taking a kitten-video break every so often may help preserve your sanity.
    – Charles Srstka
    Nov 9 at 22:49














3












3








3






My condolences, as the code you were given is a bit of a mess. First, it makes an NSData from room_name, converting the string to UTF-8 in the process, but then it doesn't use that NSData for anything other than to determine the size of a buffer, and then it converts the string to UTF-8 again and copies it into the new buffer. This is a lot more inefficient, both from a computational and a readability standpoint, than it needs to be.



If we were leaving this in Objective-C, we'd already want to clean up the code. However, in Swift, we can make this even cleaner, because String has a really nice and simple method to get us a pointer to the string's UTF-8 representation:



filename.withCString ptr in
// call whatever C-based functions expect a `const char *` pointer here



Note that the pointer you get here is immutable. If the C functions you're calling expect to be able to modify the buffer, you'll want to make a copy instead. There are a few ways to do this, but the easiest is probably just to:



guard var data = filename.data(using: .utf8) else 
// handle this error somehow


data.withUnsafeMutableBytes (ptr: UnsafeMutablePointer<Int8>) in
// call whatever C-based functions expect a `char *` pointer here
// (if you need `unsigned char *`, use `UInt8` instead of `Int8`)






share|improve this answer














My condolences, as the code you were given is a bit of a mess. First, it makes an NSData from room_name, converting the string to UTF-8 in the process, but then it doesn't use that NSData for anything other than to determine the size of a buffer, and then it converts the string to UTF-8 again and copies it into the new buffer. This is a lot more inefficient, both from a computational and a readability standpoint, than it needs to be.



If we were leaving this in Objective-C, we'd already want to clean up the code. However, in Swift, we can make this even cleaner, because String has a really nice and simple method to get us a pointer to the string's UTF-8 representation:



filename.withCString ptr in
// call whatever C-based functions expect a `const char *` pointer here



Note that the pointer you get here is immutable. If the C functions you're calling expect to be able to modify the buffer, you'll want to make a copy instead. There are a few ways to do this, but the easiest is probably just to:



guard var data = filename.data(using: .utf8) else 
// handle this error somehow


data.withUnsafeMutableBytes (ptr: UnsafeMutablePointer<Int8>) in
// call whatever C-based functions expect a `char *` pointer here
// (if you need `unsigned char *`, use `UInt8` instead of `Int8`)







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 9 at 22:38

























answered Nov 9 at 22:30









Charles Srstka

12k31333




12k31333











  • To make things worse, all of the comments are in Chinese.
    – temp_
    Nov 9 at 22:47






  • 1




    @temp_ Hang in there. Taking a kitten-video break every so often may help preserve your sanity.
    – Charles Srstka
    Nov 9 at 22:49

















  • To make things worse, all of the comments are in Chinese.
    – temp_
    Nov 9 at 22:47






  • 1




    @temp_ Hang in there. Taking a kitten-video break every so often may help preserve your sanity.
    – Charles Srstka
    Nov 9 at 22:49
















To make things worse, all of the comments are in Chinese.
– temp_
Nov 9 at 22:47




To make things worse, all of the comments are in Chinese.
– temp_
Nov 9 at 22:47




1




1




@temp_ Hang in there. Taking a kitten-video break every so often may help preserve your sanity.
– Charles Srstka
Nov 9 at 22:49





@temp_ Hang in there. Taking a kitten-video break every so often may help preserve your sanity.
– Charles Srstka
Nov 9 at 22:49


















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234022%2fconverting-objective-c-memcpy-to-swift%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)