我有一个函数给出两个整数并返回一个字符串.现在我有这个:
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)
然后,您需要为要填充的函数分配内存.这使您可以更多地选择分配字符串的位置.
在这种情况下,尽管函数中需要一些数学来获得长度,并且没有理由拥有除所需大小之外的任何大小的缓冲区.缓冲区的大小没有上限(不管是否合理).
在返回给定输入时动态找到长度的字符串时,什么是良好的做法?
我在内核模式程序中看到的模式是:
样品:
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)
| 归档时间: |
|
| 查看次数: |
520 次 |
| 最近记录: |