Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

c++ - How come pointer to a function be called without dereferencing?

I have a weird typedef statement in a C++ program, generated by Py++.

double radius(int);  // function to be wrapped
typedef double (*radius_function_type)(int);    
bp::def("radius", radius_function_type(&radius));   // bp::def is a function for wrapping

What I figured out so far is that the above typedef statemnt is not of the type, most of us are familiar with,

typedef complex_type simple_alias;

Rather it is a way to declare pointer to a function which takes int as argument and returns double (same as the prototype). So my question now is that, how come pointer to a function (without dereferencing) be called with address of a function as an argument? This also doesn't match with the prototype. Somebody please explain!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It doesn't declare a function pointer variable but a function pointer typedef called radius_function_type. radius_function_type(&radius) is just a (redundant) cast for the function pointer itself. (The unary & address-of operator is also redundant; for a function, radius and &radius are the same thing.)

On a low level, calling a function is just placing the arguments somewhere according to the underlying calling convention (usually on the stack) and then jumping to a memory address. So the compiler can call a function with just a pointer if it knows the function pointer type (function signature) and the pointer value itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...