简体   繁体   English

为什么我不能在未链接的DLL上调用方法,但可以做到这一点? C ++

[英]Why can't I call methods on unlinked DLL but can do this ? C++

So I've got DLL Alice and DLL Bob. 所以我有了DLL Alice和DLL Bob。 I cannot call each others methods. 我不能互相调用方法。 But there's one bridge. 但是有一座桥。 I can assign a pointer (I'll say the pointer from now on) from either DLL and read it in either DLL. 我可以从任何一个DLL中分配一个指针(从现在开始我要说指针),然后在任何一个DLL中读取它。 But if I assign the pointer to be an instance of a class defined in Alice, I cannot call it's methods from Bob and vice versa. 但是,如果我将指针分配为Alice中定义的类的实例,则无法从Bob调用它的方法,反之亦然。 I also cannot access it's members. 我也无法访问它的成员。 They are simply not linked (I get LNK error). 它们根本没有链接(我收到LNK错误)。 So far so good. 到现在为止还挺好。

And now, to the question. 现在,这个问题。 I've created the same class (just different name - let's call it MirrorClass) in Alice and in Bob. 我在Alice和Bob中创建了相同的类(只是名称不同-我们称它为MirrorClass)。 When I assign the pointer (both DLLs can access it) an instance of the MirrorClass created in Alice, I still cannot call it's methods from Bob. 当我分配指针(两个DLL都可以访问它)时,在Alice中创建MirrorClass的实例,我仍然无法从Bob调用它的方法。 But what I can do is pretend (explicit casting) it's an instance from Bob's MirrorClass and it'll call Bob's methods defined in Bob's version of MirrorClass and everything still works. 但是我能做的是假装 (显式强制转换)它是Bob的MirrorClass的一个实例,它将调用Bob的MirrorClass版本中定义的Bob的方法,并且一切仍然有效。 Even though it was Alice's instance of MirrorClass. 即使它是Alice的MirrorClass实例。 Obviously once I change the layout of MirrorClass, it stops working. 显然,一旦更改MirrorClass的布局,它就会停止工作。

How is that even possible ? 这怎么可能呢 ? I guess it has something to do with virtual addresses maybe, or perhaps every DLL has it's own address space. 我想这可能与虚拟地址有关,或者也许每个DLL都有自己的地址空间。 But then, objects are just pointers, so from my understanding you wouldn't even need linking, so I'm really off with my understanding of this. 但是然后,对象只是指针,因此,据我了解,您甚至不需要链接,因此我对这方面的理解真的很差。

Thanks for every advice. 感谢您的每条建议。

If you have a pointer to a class, to use the methods the class vtbl must be defined (for example, using an abstract class (pure virtual functions)). 如果您有一个指向类的指针,则要使用这些方法,必须定义类vtbl(例如,使用抽象类(纯虚函数))。 That is how COM works in Windows, for example. 例如,这就是COM在Windows中的工作方式。

Now If you got the same interface in both DLLs and the same compiler build, the first vtbl would be the same with the second, which make hard-casting from A* to B* to work. 现在,如果两个DLL中都有相同的接口,并且编译器版本相同,则第一个vtbl将与第二个相同,这将使从A *到B *的强制广播工作。

This is of course UB. 当然是UB。 It may or it may not work. 它可能会或可能不会起作用。

The DLLs share the same address space when loaded into the same process, and each one can use any of the other. 当DLL加载到同一进程中时,它们共享相同的地址空间,并且每个DLL可以使用其他任何一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM