简体   繁体   中英

Does C++ pointers work across EXEs and DLLs

I've a C++ application which is having many static ibs (*.lib) and DLLs. I'm creating an object in my EXE then i keep passing the pointer to this object from 1 library to another library using function calls.

During this process when this pointer moves from main EXE to DLL's function, i wanted to understand will it have any issue or do i need to take care any precautions.

Main.EXE with 3 static libs (A.lib, B.lib,C.lib) Main.EXE also links

with 2 DLL's - d1.dll, d2.dll. Each of these static library and DLL

also statically links to a static library X.lib.

Call Flow :

main() in main.EXE calls AFunc() in A.lib and passes a pointer to an object of some class X which is in X.lib.

Now AFunc() in A.lib calls BFunc() in B.lib & passes the "same pointer to an object of class X" which is in X.lib.

Now BFunc() in B.lib calls CFunc() in C.lib & passes the "same pointer to an object of class X" which is in X.lib.

Now CFunc() in C.lib calls D1Func() in D1.DLL & passes the "same pointer to an object of class X" which is in X.lib.

Now D1Func() in D1.DLL calls D2Func() in D2.DLL & passes the "same pointer to an object of class X" which is in X.lib.

My query is will the pointer passing across CFunc() in C.lib (part of main.EXE) AND the D1Func() of D1.DLL work ?

The short answer is - of course it will work. otherwise your process could not have communicated with any important dlls like kernel32 and user32 .

For example, the function HeapAlloc gets a pointer to a heap as the first argument and returns a pointer to the allocated memory. the function itself is implemented in kernel32.dll . if you couldn't pass a pointer to a dll or lib, this would never work.

Another issue to consider is - assuming we have a pointer to a C++ object, the fact that the pointer itself is valid across binaries,it doesn't mean that the object is treated the same in the parent EXE and the callee DLL. you need to make sure that the two binaries are ABI compatible. for example, passing a pointer of std::string from an exe that was compiled under VC++ to a DLL that was compiled under GCC is a bad idea.

Yes, that should work. Actually that's how plugins work.

How a plugin works: A program loads a DLL/shared-library, and passes its "interface" pointer to the plugin, where a plugin then uses this interface to implement new functionality in the program. You can use dynamic_cast to verify that the pointer is compatible with the interface you're assuming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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