我目前正在阅读this question,其中显示了有关使用void **
作为参数从函数返回指针的问题。
我的代码大多以状态码作为返回值,现在我正在寻找其他方法来返回这些指针和状态码。因此,我目前看到了两个选择,但没有一个能让我感到高兴。可能我想得有些迟。
// Output status through return value and the pointer through parameter
// - seems to be problematic because it requires casting to void **, which is invalid
int myfunc(void **output);
// Output status through return value, pointer through struct
// - seems to add unnecessary complexity to the interface
struct some_output { void *value };
int myfunc(struct some_output *output);
// Output pointer through return value, status through parameter
// - breaks consistency with other interfaces which always return the status code
void *myfunc(int *status);
现在,我想知道是否还有其他替代的优雅方法可以从我没有想到的没有“缺点”的函数中返回指针和状态代码?
使用'C',当函数仅限于返回单个值时,没有一种完美的方法。几乎没有常用的模式,后面是各种可用的API。考虑使用一种经过验证的,次于完美的方法:
int状态=函数(*输出,输入);
int结果= function(*输出,输入);带有扩展的错误代码。
bool成功= function(*输出,输入);有回调错误
结构结果* res = function(input,struct errro ** error)
当引入通用调用时,通常通常将输出和错误对象放在同一位置。在许多情况下,输出被放置为第一个参数,错误/异常被放置在末尾。
我同意@Mat的用法:
typedef Gret struct generic_ret;
struct generic_ret {
int Status;
union {
void *p;
DialPlan *d;
};
}
...
Phone = GetPhone(...);
if (Phone.Status == 0) {
Dial(Phone.d);
...
}
继续进行下去,您将最终在Go中进行编程...状态和指针的另一种[[classic方法是保留比0多的指针值:
extern DialPlan *DP_NoService, *DP_BadNumber, *DP_Broke, ...;
extern bool IsDialError(DialPlan *p);
....
static DialPlan *DP_FirstError = 0,
*DP_NoService = (void *)1,
*DP_BadNumber = (void *)2,
*DP_LastError = (void *)10;
bool IsDialError(DialPlan *p) {
return (p > DP_FirstError && p < DP_LastError);
}
或者,如果您更喜欢安全外观:
static DialPlan Errors[10]; static DialPlan *DP_NoService = Errors + 0, *DP_BadNumber = Errors + 1, ... *DP_LastError = Errors + 9;