Tips on using dylib/dll


#1

Hi all,
I need to thank aviram2k for encouraging me to write this and also for his help in cleaning up the code. We were discussing the ways in which dylibs and dlls can be used. Hope it would useful for some else.

These are some of the methods which would be useful while using dll/dylib

I normally put them in a macro and then use them because i dont like putting in too many if statements in my code.

#if WIN32
   #include <windows.h> 
   #define DYNAMIC_LIBRARY_LOAD(X) ::LoadLibrary(X)
   #define DYNAMIC_LIBRARY_INSTANCE HMODULE
   #define DYNAMIC_LIBRARY_FREE ::FreeLibrary
   #define DYNAMIC_LIBRARY_LOAD_PROC ::GetProcAddress
   #define THREAD_HANDLE HANDLE
   #define THREAD_RETURN_TYPE DWORD
   #define CREATE_THREAD(X1,X2,X3) X1=::CreateThread(0L, 0L, (LPTHREAD_START_ROUTINE)X2, X3, 0L, 0L)
#else
   #include <dlfcn.h> 
   #define DYNAMIC_LIBRARY_LOAD(X) dlopen(X,RTLD_LAZY)
   #define DYNAMIC_LIBRARY_INSTANCE void*
   #define DYNAMIC_LIBRARY_FREE dlclose
   #define DYNAMIC_LIBRARY_LOAD_PROC dlsym
   #define THREAD_HANDLE pthread_t
   #define THREAD_RETURN_TYPE void*
   #define CREATE_THREAD(X1,X2,X3) pthread_create(&X1, 0L, (void*(*)(void*))X2, (void*)X3)
   #define EXPORT_CLASS
#endif 

Now we have the methods to load unload symbols, next thing we need to do is export the symbols. Now this part part of code is again different on mac and windows.

On windows

#ifndef PROJECT_DATA_EXPORT
  #define PROJECT_DATA_EXPORT
#endif 

#ifdef PROJECT_ACCESS
   #define PROJECT_DATA_EXPORT __declspec(dllexport) 
#elif defined (PROJECT_DLL)
   #define PROJECT_DATA_EXPORT __declspec(dllimport)
#endif 

What am doing is defining a macro which can be any name, not just the project name. Now in my dll project i need to export the symbols, so am checking if the macro is defined i export the symbols
In the else part my importing the symbols this is for the project which is using my dll, the project which uses my dll has to import all the symbols.

On mac we actually have two options when it comes to exporting the symbols.

They are actually explained in a much better way in these links

General way of exporting symbols on mac and pc

http://gcc.gnu.org/wiki/Visibility

exporting symbols on mac

http://developer.apple.com/DOCUMENTATION/DeveloperTools/Conceptual/CppRuntimeEnv/Articles/SymbolVisibility.html