我的C++知识很臭。我有Apple提供的代码,通常他们提供了不完整的解决方案。

在此代码上,它们提供了两个空的方法 header :

- (NSString *)encodeBase64:(const uint8_t *)input length:(NSInteger)length
- (NSString *)decodeBase64:(NSString *)input length:(NSInteger *)length

从理论上讲,这些方法应调用两个C++样式函数,但是由于我的C++知识使无穷平方加一,所以请填写???。
- (NSString *)encodeBase64:(const uint8_t *)input length:(NSInteger)length
{
   // I need to call base64_encode and return its results as string... is this correct?

   return [NSString stringWithUTF8String:
       base64_encode(input, ???)];
    // ??? I need to pass a NSInteger to a size_t... how do I do that?
}


- (NSString *)decodeBase64:(NSString *)input length:(NSInteger *)length
{

// ??? = this method receives a NSInteger *length variable. How do I pass that
// to a size_t * variable required by base64_decode?

    NSString *st = [[NSString alloc] initWithBytes:
                    base64_decode([input UTF8String], ???)
                                            length:&length
                                          encoding: NSUTF8StringEncoding];

    return st;
}

这两个方法调用这些C++函数
char* base64_encode(const void* buf, size_t size)
{
   // bla bla bla
}

void* base64_decode(const char* s, size_t* data_len_ptr)
{
    // bla bla bla
}

谢谢。

最佳答案

首先,如果您想进行base64编码/解码,您会发现从一个正确的示例开始比较容易。马特·加拉格尔(Matt Gallagher)在Base64 encoding options on the Mac and iPhone中给出了简单的食谱。

如果您真的想充实您的示例,请记住NSIntegerlong,而size_tunsigned long。您可以将以下行替换为以下行:

- (NSString *)encodeBase64:(const uint8_t *)input length:(NSInteger)length
{
    return [NSString stringWithUTF8String:base64_encode(input, (size_t)length)];
}

- (NSString *)decodeBase64:(NSString *)input length:(NSInteger *)length
{
    size_t retLen;
    uint8_t *retStr = base64_decode([input UTF8String], &retLen);
    if (length)
        *length = (NSInteger)retLen;
    NSString *st = [[[NSString alloc] initWithBytes:retStr
                                        length:retLen
                                      encoding:NSUTF8StringEncoding] autorelease];
    free(retStr);    // If base64_decode returns dynamically allocated memory
    return st;
}

(如果要在ARC下编译,请删除自动发布。)

请注意,不能保证任意字节序列都是有效的UTF-8字符串。该API允许您发送任意字节,但假定它将解码为有效的UTF-8字符串,但不一定正确。

关于c++ - 将NSInteger传递给size_t,将NSInteger *传递给size_t *,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11637965/

10-11 22:54
查看更多