C 中可以通过函数指针调用静态函数吗?
我认为源文件中的静态函数不能直接从文件外部调用。但是,如果我设法将指向该函数的指针放入另一个文件中,我可以从该文件中调用该函数吗?如果是,与简单地使函数成为非静态相比,是否有任何情况我们希望采取这条路线?
I believe that a static function in a source file cannot be called directly from outside the file. However, if I somehow manage to get a pointer to this function into another file, can I then call this function from that file. If yes, is there any scenario when we would like to take this route as compared to simply making the function non-static ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,您可以通过传递指向静态函数的指针来导出它们。这是在 C 中实现工厂模式的常用方法,您可以在其中隐藏某个对象的实现使用它们的模块中的一大堆函数,并有一个
FuncPtr_t GetFunction( enum whichFunctionIWant)
将它们分发给消费者。这就是许多动态链接实现的工作原理。Yes, you can export static functions by handing out pointers to them. This is a common means of implementing the Factory pattern in C, where you can hide the implementations of a whole bunch of functions from the modules that use them, and have a
FuncPtr_t GetFunction( enum whichFunctionIWant)
that hands them out to consumers. That's how many dynamic linking implementations work.是的,这是完全可能的。该函数对链接器不可见,但它存在于可执行文件中。您随时可以跳转到其地址。
但我不确定场景。也许您希望其他人仅在调用其他函数(当然是非静态的)之后才调用您的函数。所以你让他们获取它,然后他们就可以调用它。
Yes, it's perfectly possible. The function isn't visible to the linker, but it's there in the executable. You can always jump to its address.
I am not sure about scenarios though. Maybe you want others to only call your function after they called some other function (non-static of course). So you have them obtain it, and then they can call it.
正如另一个人提到的,你可以做到。您可能想要的一个例子是某种“驱动程序”。您可以传回包含打开、关闭、读取和写入函数的结构,而不必公开访问实际的函数。
As the other mentioned, you can do it. An example of why you might want to is for some sort of "driver". You might pass back a structure containing the open, close, read, and write functions without having to make the actual functions publicly accessible.
是的,你可以。如果必须调用一个需要指向函数的指针作为回调的函数,则可以使用 static,这样函数符号就不会污染全局命名空间,也不会导致链接器冲突。最常用的例子可能是 qsort:
Yes, you can. If you have to call a function that expects a pointer to a function as a callback, you can use static so that the function symbol does not pollute the global namespace and does not cause linker conflicts. The most used example is probably qsort:
是的,文件中的非静态函数可以将指向静态函数的指针返回到您喜欢的任何地方。
Yes, a non-static function in your file can return a pointer to a static function to anywhere you like.
是的,你可以,你总是可以自己尝试一下并找出:
file1.c
file2.c
Yes you can, you could always try it for yourself and find out:
file1.c
file2.c
将一个小的静态函数定义为其他函数的工作函数通常很有用。看一下标准的 qsort 示例:它需要一个比较函数,并且通常最好将该比较函数设为静态(例如,因为它在其他地方没有用,并且因为 qsort< /code> 希望它有一些不漂亮的签名)。
It is often useful to define a small static function as a worker function for some other one. Look at the standard
qsort
for an example: it expects a comparing function, and very often it is better to make that comparing function static (e.g. because it is not useful elsewhere, and becauseqsort
wants it to have some unpretty signature).