【问题标题】:Rewriting a returned pointer to an output parameter将返回的指针重写为输出参数
【发布时间】:2010-12-23 19:19:21
【问题描述】:

我正在使用 openSSL 库,它需要我重新学习指针,我遇到了困难。

我有一个objective-c方法:

-(unsigned char *)encryptTake1:(unsigned char *)input inputLength:(int)inLen outputLength:(int*)outLen;

它获取一些数据,对其进行加密并返回指向数据的指针和数据的长度作为输出参数。

我想更改此设置,以便将加密数据也作为输出参数处理,并且返回值用于指示成功或失败。这就是我所拥有的:

-(int)encryptTake2:(unsigned char *)input inputLength:(int)inLen output:(unsigned char *)output outputLength:(int*)outLen;

这不起作用。我究竟做错了什么?我认为问题在于(unsigned char *) 是错误的。如果(unsigned char *) 错误,那么我想我还需要更改在方法中引用output 的方式。怎么样?

【问题讨论】:

    标签: objective-c function pointers


    【解决方案1】:

    这取决于您如何处理内存分配。

    -encryptTake1: 返回什么?如果它返回调用者必须释放的新分配的缓冲区,那么您将在 encryptTake2 中使用 unsigned char**:

    -(int)encryptTake2:(unsigned char *)input inputLength:(int)inLen output:(unsigned char **)outputPtr outputLength:(int*)outLen
    {
        *outputPtr = malloc(1024);
        unsigned char* output = *outputPtr;
        strcpy(output, "hello");
        ...
    }
    

    【讨论】:

    • 谢谢 - 搞定了!我也对调用函数中的& 和* 感到困惑。在调用函数中,var 定义为unsigned char *,并在函数调用中以& 为前缀。在encryptTake2: 中,所有对var 的引用都以* 为前缀。我需要重新阅读 C 书的第 5 章。
    猜你喜欢
    • 2013-03-25
    • 2019-08-22
    • 2019-11-18
    • 2018-05-30
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多