Objective-C 使用动态绑定,但如何实现呢?

发布于 2024-08-09 22:36:17 字数 98 浏览 5 评论 0原文

我知道 Objective-C 对所有方法调用都使用动态绑定。这是如何实施的? Objective-c 是否在编译前“转换为 C 代码”并仅使用 (void*) 指针来处理所有内容?

I know that Objective-C uses dynamic binding for all method calls. How is this implemented? Does objective-c "turn into C code" before compilation and just use (void*) pointers for everything?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷…雨湿花 2024-08-16 22:36:17

从概念上讲,发生的事情是有一个调度程序库(通常称为 Objective C 运行时),编译器将如下内容转换为:

[myObject myMethodWithArg:a andArg:b ];

然后

//Not exactly correct, but close enough for this
objc_msgSend(myObject, "myMethodWithArg:andArg:", a, b);

运行时处理所有绑定和调度,找到合适的函数,并用这些参数调用它。简单地说,您可以将其视为有点像哈希查找;当然,这比现实要复杂得多。

还有很多与方法签名等相关的问题(C 不编码类型,因此运行时需要处理它)。

Conceptually, what is going on is that there is a dispatcher library (commonly referred to as the Objective C runtime), and the compiler converts something like this:

[myObject myMethodWithArg:a andArg:b ];

into

//Not exactly correct, but close enough for this
objc_msgSend(myObject, "myMethodWithArg:andArg:", a, b);

And then the runtime deals with all the binding and dispatch, finds an appropriate function, and calls it with those args. Simplistically you can think of it sort of like a hash lookup; of course it is much more complicated that then in reality.

There are a lot more issues related to things like method signatures (C does not encode types so the runtime needs to deal with it).

べ繥欢鉨o。 2024-08-16 22:36:17

每个 Objective C 方法都作为(实际上)C 函数“在幕后”实现。该方法有一条与之关联的消息(文本字符串),并且该类有一个将消息字符串与 C 函数相匹配的查找表。因此,当您调用 Objective C 方法时,真正发生的是将消息字符串发送到对象,然后该对象在其类的方法查找表中查找关联的 C 函数并运行它。

Objective C 还有更多内容,比如对象如何通过转发来处理它们不理解的消息,它们如何缓存消息到方法的查找,等等,但这只是基础知识。

C++ 类似,只不过类没有消息表,而是有其他称为“vtable”的东西,并且您不是通过文本字符串调用方法,而是通过其在 vtable 中的偏移量调用方法。这是静态绑定的一种形式,可以在一定程度上加快执行速度,但不如动态绑定灵活。

Each Objective C method is implemented "under the hood" as (in effect) a C function. The method has a message (text string) associated with it, and the class has a lookup table that matches the message string with the C function. So when you call an Objective C method, what really happens is you send a message string to the object, and the object looks up the associated C function in its class's method lookup table and runs that.

There's more to it with Objective C, like how objects handle messages they don't understand by forwarding them, how they cache message-to-method lookups, and so on, but that's the basics.

C++ is similar, except instead of the class having a message table, it has something else called a "vtable", and you invoke a method not via a text string, but via its offset into the vtable. This is a form of static binding, and speeds up execution somewhat, but is less flexible than dynamic binding.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文