문제

I'm working with sockets and trying to simply write a string to the socket. I found a couple of examples on how to do this, such as the following example (oStream is an NSOutputStream). This is all within the NSStreamEventHasSpaceAvailable.

uint8_t buffer[11] = "I send this";             
int len;
len = [oStream write:buffer maxLength:sizeof(buffer)];

That works great. So I tried modifying it to make it customizable by getting the bytes of out an NSString.

int len;
NSString* strId;
strId = @"string will be customized with several lines of code here";

uint8_t buffer[[strId lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];                       
[strId getBytes:buffer maxLength:sizeof(buffer) usedLength:NULL encoding:NSASCIIStringEncoding options:NULL range:NSRangeFromString(strId) remainingRange:NULL];
len = [oStream write:buffer maxLength:sizeof(buffer)];

This isn't working at all. It writes complete gibberish into the buffer (probably the bytes) and I'm getting a warning for the getBytes line of "passing argument 5 of getBytes makes integer from pointer without a cast."

Sorry if this has been asked before, couldn't find an answer from searching and it looked like the problem should be very simple to fix. Thanks!

EDIT: I've found something that seems to work, but I'm not sure if it's proper programming of something like this. Please see the answer below. Is that dangerous code to be using in this situation?

도움이 되었습니까?

해결책

다른 팁

After more research I've found that this seems to work:

len = [oStream write:[[strId dataUsingEncoding:NSASCIIStringEncoding] bytes] maxLength:[strId lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];

I feel as if that's not very safe since it's using a couple of different ways of getting the data into the NSOutputStream as well as the length. Is there going to a a problem doing it like this?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top