我对C比较陌生,但是这个语法是什么意思呢?
typedef Value (*NativeFn)(int argCount, Value* args);
据我所知,这里使用"Value“来定义新名称的类型。我不理解的部分是(*NativeFn)(int argCount, Value* args);,这部分是什么意思?
发布于 2020-08-12 05:32:35
其他人正确地说:
typedef Value (*NativeFn)(int argCount, Value* args);为指向函数的指针类型创建一个类型定义函数名称NativeFn。
typedef的语法,就像一般的C声明的语法一样,可能会令人困惑。typedef特性实际上是在声明语法建立之后添加到语言中的,并且必须在不破坏任何其他内容的情况下添加。解决方案是在语法上将typedef视为存储类说明符(尽管它在语义上不是)。typedef以外的存储类说明符有extern、static、_Thread_local、auto和register。
这意味着您可以通过将关键字typedef替换为例如static来理解typedef声明。当static声明声明某个类型的对象(或函数)时,相应的typedef声明将创建具有相同名称和类型的类型定义。所以这就是:
static int foo;创建类型为int (具有静态存储持续时间)的对象foo,而如下所示:
typedef int foo;创建一个类型名称foo,它是类型int的别名。
所以如果你的声明是:
static Value (*NativeFn)(int argCount, Value* args);它会将NativeFn定义为指向函数的指针对象(函数返回Value类型的结果)。将static替换为typedef意味着NativeFn是引用同一指向函数类型的指针的类型名。
同样重要的是要记住,typedef不会创建新类型。它为现有类型创建一个新名称。
发布于 2020-08-12 04:42:37
考虑一下这样的记录
Value (int argCount, Value* args)它表示具有返回类型Value和两个类型为int和Value *的参数的函数类型。
标识符Value在其他地方声明,例如可以是一个类型的别名。
要将指针类型的别名引入函数类型,可以编写
typedef Value (*NativeFn)(int argCount, Value* args);因此,如果你有一个函数,例如
Value some_function(int argCount, Value* args);然后,您可以通过以下方式使用typedef别名定义来声明指向此函数的指针
NativeFn pointer_to_some_function = some_function; 发布于 2020-08-12 04:47:42
井,
typedef (*NativeFn)(int argCount, Value* args)手段
NativeFn是一个返回Value的function type(can also be called "a pointer to function" or "function pointer"),它接受int和Value *作为参数。
如果你对我们为什么以及如何使用它感到困扰,那么阅读下面的代码,特别是注释,你会很清楚(*NativeFn)(int argCount, Value* args)的含义和使用方法:
#include <stdio.h>
// note: "Value" is a type declared earlier
// for discussions sake we're declaring our own Value type
typedef struct __value {
int x, y;
} Value;
// now, the following tells us that:
// "NativeFn" is some function type that returns "Value"
typedef Value (*NativeFn)(int argCount, Value* args);
// okay, see how to use "NativeFn"
// for use "NativeFn" we've to declare some function first
// which takes two arguments same as "NativeFn" and return "Value"
Value someFun(int argCount, Value* args) {
// do something argCount and args
// at last it should return some "Value" type
Value v = {2, 3};
return v;
}
int main() {
// now its time to use "NativeFn"
NativeFn fun;
fun = someFun; // notice we can use fun as a variable and assign a
// function to it, which must take arguments same as "NativeFn" and returns "Value" type
Value input = {10, 12};
Value output = fun(1, &input); // note, we're calling "fun", not "someFun"
// it'll output 2, 3, cause we're returning Value v = {2, 3} from "someFun"
printf("(x, y): %d, %d\n", output.x, output.y);
return 0;
}如果你有任何问题,请在评论中问我...
https://stackoverflow.com/questions/63365936
复制相似问题