Re: Query regarding dynamic library
Re: Query regarding dynamic library
- Subject: Re: Query regarding dynamic library
- From: Alastair Houghton <email@hidden>
- Date: Mon, 10 Dec 2007 14:49:57 +0000
On 10 Dec 2007, at 09:32, parag vibhute wrote:
Dynamic library mentions following statement (Page 28):
Dynamic libraries that make a class available to its clients must
include the virtual keyword in the declaration of all the class's
methods, except for its constructors and destructors. For example,
following listing shows the declaration for the Person class.
class Person {
private:
char _person_name[30];
public:
Person();
virtual void set_name(char person_name[]);
virtual char* name();
};
Why is it necessary to include virtual keyword here?
(I assume this is talking about using dlopen() to load the code.)
The reason is that if you do
class Foo {
public:
void bar();
};
then you call it from code like so
void my_function(Foo *foo) {
foo->bar();
}
the compiler does something like this:
Foo::bar(foo);
which uses the linker to look up the symbol "Foo::bar" and substitutes
it into the code at build time.
The only way to get around this is to use weak linking, and it will
only work with dlopen()-loaded libraries if you also disable the two-
level namespace feature (I think) and pass RTLD_GLOBAL when loading
them. Doing that is pretty unpleasant.
If, on the other hand, you do
class Foo {
public:
virtual void bar();
};
and then you call it from code, e.g.
void my_function(Foo *foo) {
foo->bar();
}
the compiler actually does something like this:
(*foo->vtable->bar)(foo);
i.e. it obtains the address of the method to call *from the object*,
at run-time, rather than by using the linker at build time. It isn't
using a symbol at all to do it, so no linking is necessary.
Hopefully that makes sense.
Kind regards,
Alastair.
--
http://alastairs-place.net
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden