CGameInterface.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "stdafx.h"
  2. #include "CGameInterface.h"
  3. #ifdef _WIN32
  4. #define WIN32_LEAN_AND_MEAN //excludes rarely used stuff from windows headers - delete this line if something is missing
  5. #include <windows.h> //for .dll libs
  6. #else
  7. #include <dlfcn.h>
  8. #endif
  9. /*
  10. * CGameInterface.cpp, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. template<typename rett>
  19. rett * createAnyAI(CCallback * cb, std::string dllname, std::string methodName)
  20. {
  21. char temp[50];
  22. rett * ret=NULL;
  23. rett*(*getAI)();
  24. void(*getName)(char*);
  25. std::string dllPath;
  26. #ifdef _WIN32
  27. dllPath = LIB_DIR "/" +dllname+".dll";
  28. HINSTANCE dll = LoadLibraryA(dllPath.c_str());
  29. if (!dll)
  30. {
  31. tlog1 << "Cannot open AI library ("<<dllPath<<"). Throwing..."<<std::endl;
  32. throw new std::string("Cannot open AI library");
  33. }
  34. //int len = dllname.size()+1;
  35. getName = (void(*)(char*))GetProcAddress(dll,"GetAiName");
  36. getAI = (rett*(*)())GetProcAddress(dll,methodName.c_str());
  37. #else
  38. dllPath = LIB_DIR "/" + dllname + ".so";
  39. void *dll = dlopen(dllPath.c_str(), RTLD_LOCAL | RTLD_LAZY);
  40. if (!dll)
  41. {
  42. tlog1 << "Cannot open AI library ("<<dllPath<<"). Throwing..."<<std::endl;
  43. throw new std::string("Cannot open AI library");
  44. }
  45. getName = (void(*)(char*))dlsym(dll,"GetAiName");
  46. getAI = (rett*(*)())dlsym(dll,methodName.c_str());
  47. #endif
  48. getName(temp);
  49. tlog0 << "Loaded AI named " << temp << std::endl;
  50. ret = getAI();
  51. if(!ret)
  52. tlog1 << "Cannot get AI!\n";
  53. ret->dllName = dllname;
  54. return ret;
  55. }
  56. CGlobalAI * CAIHandler::getNewAI(CCallback * cb, std::string dllname)
  57. {
  58. return createAnyAI<CGlobalAI>(cb, dllname, "GetNewAI");
  59. }
  60. CBattleGameInterface * CAIHandler::getNewBattleAI( CCallback * cb, std::string dllname )
  61. {
  62. return createAnyAI<CBattleGameInterface>(cb, dllname, "GetNewBattleAI");
  63. }