[英]What is the best way to convert this java code into Objective C code?
public byte[] toBytes() {
size = 12;
ByteBuffer buf = ByteBuffer.allocate(size);
buf.putInt(type.ordinal());//type is a enum
buf.putInt(id);
buf.putInt(size);
return buf.array();
}
@Override
public void fromBytes(byte[] data) {
ByteBuffer buf = ByteBuffer.allocate(data.length);
buf.put(data);
buf.rewind();
type = MessageType.values()[buf.getInt()];
id = buf.getInt();
size = buf.getInt();
}
我有兩個java方法,並想編寫一個目標C方法。對於第一個方法,我將其編寫為一個Objective C代碼,例如
- (NSMutableData *) toBytes{
size = 12;
NSMutableData *buf = [[NSMutableData alloc] initWithCapacity:size];
NSData *dataType = [NSData dataWithBytes: &type length: sizeof(type)];
NSData *dataId = [NSData dataWithBytes: &msgId length: sizeof(msgId)];
NSData *dataSize = [NSData dataWithBytes: &size length: sizeof(size)];
[buf appendData:dataType];
[buf appendData:dataId];
[buf appendData:dataSize];
[dataType release];
[dataId release];
[dataSize release];
return buf;
}
但是不確定如何回讀...如果只向緩沖區中添加一個數據,但總共添加了三個數據,這樣會更容易,所以我不知道如何回讀這些數據。 。
LCYSoft注意:我正在將其作為社區Wiki。 請更正任何問題。 我沒有編譯這個。 因為您發布了一個方向並且真的想要一個答案,所以我提供了一個方向。 抱歉,我有點忙。
這演示了兩個方向,並在OP上進行了擴展:
typedef enum t_mon_enum_type {
MONEnum_Edno = 1,
MONEnum_Dve = 2,
MONEnum_Tre = 3
} t_mon_enum_type;
@interface MONObject : NSObject
{
t_mon_enum_type type;
int msgId;
int size;
}
@end
@implementation MONObject
/* ... */
- (NSMutableData *)dataRepresentation
{
const int typeAsInt = (int)type;
const size_t capacity = sizeof(typeAsInt) + sizeof(msgId) + sizeof(size);
NSMutableData * data = [[NSMutableData alloc] initWithCapacity:capacity];
[data appendBytes:&typeAsInt length:sizeof(typeAsInt)];
[data appendBytes:&msgId length:sizeof(msgId)];
[data appendBytes:&size length:sizeof(size)];
return [data autorelease];
}
- (BOOL)isDataRepresentationValid:(NSData *)data { /* @todo */ }
- (BOOL)restoreFromDataRepresentation:(NSData *)data
{
if (![self isDataRepresentationValid]) {
return NO;
}
NSRange range = { 0, 0 };
int tmp = 0;
/* restore `type` */
range.length = sizeof(tmp);
[data getBytes:&tmp range:range];
type = (t_mon_enum_type)tmp;
/* advance read position */
range.location += range.length;
/* restore `msgId` */
range.length = sizeof(msgId);
[data getBytes:&msgId range:range];
/* advance read position */
range.location += range.length;
/*
setting the length here is redundant in this case, but it's how we
write it when dealing with more complex pod types.
*/
range.length = sizeof(size);
[data getBytes:&size range:range];
return YES;
}
我不會為您重寫程序,但我將提供一個提示:
您可以在objc程序中使用c ++。 具體來說,您可以編譯為C(.c),ObjC(.m),C ++(.cpp)和ObjC ++(.mm)。 注意:每種語言都有一個通用的擴展名。 (默認情況下)編譯器將使用文件擴展名所隱含的語言進行編譯。
現在,許多Java程序與c ++程序更加相似。 如果要移植程序,還應考慮用c ++編寫它,因為該程序通常更接近於Java變體。
對於objc,您可能會使用CF/NS-MutableData
對於C ++,您可以使用std::vector
祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.