質問

For example, in Python I can use getargspec from inspect to access a function's arguments in the follow way:

>>> def test(a,b,c):
...     return a*b*c
...
>>> getargspec(test)
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)

Is this possible to do in C at all? More specifically I am only interested in the arguments' names, I don't particularly care about their types.

役に立ちましたか?

解決

The language doesn't include anything along this line at all.

Depending on the implementation, there's a pretty fair chance that if you want this badly enough, you can get at it. To do so, you'll typically have to compile with debugging information enabled, and use code specific to a precise combination of compiler and platform to do it. Most compilers do support creating and accessing debugging information that would include the names of the parameters to a function -- but code to do it will not be portable (and in many cases, it'll also be pretty ugly).

他のヒント

No, all variable names are gone during compilation (except perhaps file-scope variables with "extern" storage duration), so you can't get the declaration names of the arguments.

No, this is absolutely impossible in C, since variable names exist only at compile time.

Probably it would be solvable via macro. You could define

#define defFunc3(resultType,name,type0,arg0name,type1,arg1name,type2,arg2name) \
...store the variable names somehow... \
...you can access the variable name strings with the # operator, e.g. #arg0name \
...or build a function with concatenation: getargspec_##name \
resultType name(type0 arg0name, type1 arg1name, type2 arg2name )

and then declare your function with this macro:

defFunc3( float, test, float, a, float, b, float, c ) {
  return a * b * c;
}

In the macro body, you could somehow store the variable names (with the stringification preprocessor operator) and/or the function address somewhere or create some kind of "getargspec" function (via the concatenation preprocessor operator).

But this will be definitely ugly, error prone and tricky (since you can not execute code in such a function definition directly). I would avoid such macro magic whenever possible.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top