正确的方法从函数返回一个字符串

Mat*_*att 14 c string

我有一个函数给出两个整数并返回一个字符串.现在我有这个:

char* myfunc( int a, int b, int* len )
{
    int retLen = ...
    char* ret = malloc( retLen + 1 );

    if ( len != NULL )
    {
        *len = retLen;
    }

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

但是,C库中的大多数函数都倾向于执行更类似的操作:

int myfunc( char* ret, int a, int b )
{
    ...

    return retLen;
}
Run Code Online (Sandbox Code Playgroud)

然后,您需要为要填充的函数分配内存.这使您可以更多地选择分配字符串的位置.

在这种情况下,尽管函数中需要一些数学来获得长度,并且没有理由拥有除所需大小之外的任何大小的缓冲区.缓冲区的大小没有上限(不管是否合理).

在返回给定输入时动态找到长度的字符串时,什么是良好的做法?

cly*_*yfe 7

我在内核模式程序中看到的模式是:

  1. 你可以调用函数一次,如果碰巧有一些可用的内存,则调用一些内存,如果碰巧没有,则调用null作为参数
  2. 如果你已经分配了内存并且函数找到了它,那么它会将结果放入该内存并返回OK
  3. 如果您没有传入内存,或者传递的内存太少,则该函数返回ERROR_NOT_ENOUGH_MEMORY,并将输出参数输入所需的内存.
    • 然后分配所需的内存并再次调用该函数

样品:

int myfunc(
    __out char*  output, 
    __in  size_t given, 
    __out size_t needed_or_resulted, 
    extra params ...
){
    ... implementation
}
Run Code Online (Sandbox Code Playgroud)

needed_or_resulted还可以用来传输多少给定存储在成功的情况下使用.

要像以下一样使用:

int result = myfunc(output, given, needed_or_resulted, extra params ...);
if(result == OK) {
    // all ok, do what you need done with result of size "needed_or_resulted" on "output"
} else if(result == ERROR_NOT_ENOUGH_MEMORY) {
    output = malloc(needed ...
    result = myfunc(output, given, needed_or_resulted, extra params ...);
    if(result == OK) {
        // all ok, do what you need done with result of size "needed_or_resulted" on "output"
    } else if(result == ERROR_OTHER) {
        // handle other possible errors
    } else {
        // handle unknown error
    }
} else if(result == ERROR_OTHER) {
    // handle other possible errors
} else {
    // handle unknown error
}
Run Code Online (Sandbox Code Playgroud)