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
617 views
in Technique[技术] by (71.8m points)

delegates - are there function pointers in c#?

I am trying to learn some c# coding and wondering if the c++ concept of function pointers is included in c#. I see there are such things as delegates. Are they the same concept? or do they differ on a more fundamental level?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

As others have said, you'll want to use delegates for situations in C# that you would have used function pointers for in C++. Delegates are conceptually similar to function pointers but far more pleasant to use, since they encapsulate not just the function, but also the "receiving" object which will be the "this" of the invocation.

Note that the CLR does have the concept of function pointers. If you were to take a close look at how the C# compiler generates code that constructs delegates, you'd see that it makes a managed reference to a function and passes that to a delegate constructor. There is no language feature in C# that allows you to get at the "naked" function pointer and manipulate it directly.

However, since the concept does exist in the CLR, it is theoretically possible that a future version of C# could support function pointers as a first-class concept in unsafe code, just as we support data pointers in unsafe code. What we would do in that case is (1) track the signature of the function pointer as the pointer type, and (2) emit code that uses the "calli" (call through pointer indirection) CIL opcode.

This would increase efficiency in certain obscure interop scenarios where today basically you have to make the marshalling code jump through a lot of hoops, building up delegate instances solely so that the marshaller can get at the function pointer stored in them. If we could avoid requiring the expense of delegate construction and go straight to the function pointer then those now-rare interop scenarios could become less expensive.

However, I wouldn't hold my breath waiting for that feature if I were you. We've prototyped it and it works reasonably well, but I don't think the demand is there to warrant adding it to a general-purpose language like C# at this time.


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

...