Beispiel #1
0
GCORE_END_MODULE_INTERFACE

int main(int,char**)
{
#if defined(WIN32)
  MyDll dll("testmodule.dll");
#elif defined(__APPLE__)
  MyDll dll("testmodule.bundle");
#else
  MyDll dll("testmodule.so");
#endif

  dll.initialize();

  if (dll.isLoaded())
  {
    dll.load("./conf.cfg");
  }
  else
  {
    std::cerr << "Could not load library" << std::endl;
    std::cerr << dll._getError() << std::endl;
  }

  dll.update();

  dll.reset();

  return 0;
}
Beispiel #2
0
//////////////////////////////////////////////////////////////////////////////////////////////////远程线程注入DLL
void JysNT::InjectDll(WCHAR* lpcszProcName,LPCSTR dlladdr)
{
	HANDLE processH=CreateToolhelp32SnapshottoOpenProcess(lpcszProcName);
	LPVOID AllocAddr=VirtualAllocEx(processH,0,256,MEM_COMMIT,PAGE_EXECUTE_READWRITE);
	//LastError(L"V");
	// 	CSAlloc.Format(L"%x",AllocAddr);
	// 	MessageBox(0,(LPCTSTR)CSAlloc,0,0);

	GetCurrentDirectory(MAX_PATH,pBuf);
	//LastError(L"01");

	CString dll(dlladdr);		//DLL 名字记得在前面加上 "\\"
	CSDirectory=pBuf+dll;

	int cb = ((1 + lstrlenW(CSDirectory))* sizeof(WCHAR));
	//LPCTSTR writeBuf=CSDirectory;
	//CString writeBuf;
	//writeBuf.Format(L"%s",CSDirectory);
	WriteProcessMemory(processH,AllocAddr,CSDirectory,cb,0);

	PTHREAD_START_ROUTINE addr=(PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(L"Kernel32"),"LoadLibraryW");
	//LastError(L"G");
	//CSaddr.Format(L"%x",addr);
	//MessageBox((LPCTSTR)CSaddr,0,0);
	CreateRemoteThread(processH,NULL,0,addr,AllocAddr,0,0);
}
    components::security::signed_certificate
        subordinate_certificate_authority::get_certificate(error_code& ec) const
    {
        if (0 == subordinate_certificate_authority_)
        {
            HPX_THROWS_IF(ec, invalid_status,
                "subordinate_certificate_authority::get_certificate",
                "subordinate_certificate_authority is not initialized yet");
            return components::security::signed_certificate::invalid_signed_type;
        }

        // Bind the certificate_authority_get_certificate symbol dynamically and invoke it.
        typedef void (*function_type)(
            components::security::server::certificate_authority_base*
          , components::security::signed_certificate*);

        typedef boost::function<void(function_type)> deleter_type;

        hpx::util::plugin::dll dll(
            HPX_MAKE_DLL_STRING(std::string("security")));
        std::pair<function_type, deleter_type> function =
            dll.get<function_type, deleter_type>(
                "certificate_authority_get_certificate");

        components::security::signed_certificate signed_certificate;

        (*function.first)(
            subordinate_certificate_authority_, &signed_certificate);

        return signed_certificate;
    }
    components::security::signed_certificate
        subordinate_certificate_authority::sign_certificate_signing_request(
            components::security::signed_certificate_signing_request const & signed_csr) const
    {
        HPX_ASSERT(0 != subordinate_certificate_authority_);

        // Bind the certificate_authority_sign_certificate_signing_request symbol dynamically and invoke it.
        typedef void (*function_type)(
            components::security::server::certificate_authority_base*
          , components::security::signed_certificate_signing_request const &
          , components::security::signed_certificate*);

        typedef boost::function<void(function_type)> deleter_type;

        hpx::util::plugin::dll dll(
            HPX_MAKE_DLL_STRING(std::string("security")));
        std::pair<function_type, deleter_type> function =
            dll.get<function_type, deleter_type>(
                "certificate_authority_sign_certificate_signing_request");

        components::security::signed_certificate signed_certificate;

        (*function.first)(
            subordinate_certificate_authority_
          , signed_csr
          , &signed_certificate);

        return signed_certificate;
    }
 void loadFilesystem(const char* name) {
     FilesystemDLL dll(name);
     auto res = mFilesystems.insert(std::make_pair(UTF8Handle(name), std::move(dll)));
     if (res.second == false) {
         throw std::runtime_error("Filesystem DLL already loaded");
     }
 }
Beispiel #6
0
inline bool query_information_file(
    HANDLE FileHandle, io_status_block* IoStatusBlock,
    void* FileInformation, ULONG Length, DWORD FileInformationClass)
{
    // from ZwQueryInformationFile in ntddk.h
    typedef LONG (__stdcall *func_type)(
        HANDLE, io_status_block*, void*, ULONG, DWORD);

    bool result = false;

    HMODULE dll(::LoadLibraryA("ntdll.dll"));
    if (!dll)
        return result;

    func_type func = reinterpret_cast<func_type>(
        ::GetProcAddress(dll, "NtQueryInformationFile"));
    if (func)
    {
        LONG res = (*func)(
            FileHandle, IoStatusBlock, FileInformation, Length,
            FileInformationClass);

        if (res == 0)
            result = true;
    }
    ::FreeLibrary(dll);

    return result;
}
Beispiel #7
0
static void s_TEST_SimpleDll(void)
{
    CDll dll("./","test_dll", CDll::eLoadLater);

    // Load DLL
    dll.Load();

    // DLL variable definition
    int*    DllVar_Counter;
    // DLL functions definition    
    int     (* Dll_Inc) (int) = NULL;
    int     (* Dll_Add) (int, int) = NULL;
    string* (* Dll_StrRepeat) (const string&, unsigned int) = NULL;

    // Get addresses from DLL
    DllVar_Counter = dll.GetEntryPoint_Data("DllVar_Counter", &DllVar_Counter);
    if ( !DllVar_Counter ) {
        ERR_FATAL("Error get address of variable DllVar_Counter.");
    }
    Dll_Inc = dll.GetEntryPoint_Func("Dll_Inc", &Dll_Inc );
    if ( !Dll_Inc ) {
        ERR_FATAL("Error get address of function Dll_Inc().");
    }
    Dll_Add = dll.GetEntryPoint_Func("Dll_Add", &Dll_Add );
    if ( !Dll_Add ) {
        ERR_FATAL("Error get address of function Dll_Add().");
    }
    Dll_StrRepeat = dll.GetEntryPoint_Func("Dll_StrRepeat", &Dll_StrRepeat );
    if ( !Dll_StrRepeat ) {
        ERR_FATAL("Error get address of function Dll_StrRepeat().");
    }

    // Call loaded function

    assert( *DllVar_Counter == 0  );
    assert( Dll_Inc(3)      == 3  );
    assert( *DllVar_Counter == 3  );
    assert( Dll_Inc(100)    == 103);
    assert( *DllVar_Counter == 103);
    *DllVar_Counter = 1;
    assert( Dll_Inc(0)      == 1  );

    assert( Dll_Add(3,4)    == 7  );
    assert( Dll_Add(-2,-1)  == -3 );
    
    string* str = Dll_StrRepeat("ab",2);
    assert( *str == "abab");
    delete str;

    str = Dll_StrRepeat("a",4);  
    assert( *str == "aaaa");
    delete str;

    // Unload used dll
    dll.Unload();
}
Beispiel #8
0
void LoadLocalizedResources()
{
	HMODULE hResources = NULL;

	wchar_t szLang[9];

	// user language
	if(::GetLocaleInfo(LOCALE_CUSTOM_UI_DEFAULT, LOCALE_SISO639LANGNAME2, szLang, 9) > 0)
	{
		wstring dll (L"console_");
		dll += szLang;
		dll += L".dll";
		hResources = ::LoadLibraryEx(dll.c_str(), NULL, LOAD_LIBRARY_AS_DATAFILE);

		Win32Exception ex("LoadLibraryEx", ::GetLastError());
		TRACE(L"LOCALE_CUSTOM_UI_DEFAULT LOCALE_SISO639LANGNAME2=%s dll=%s hResources=%p (%S)\n", szLang, dll.c_str(), hResources, ex.what());
	}

	// default resources are in english
	if(!hResources && ::_wcsicmp(szLang, L"eng") == 0) return;

	// system language
	if(!hResources && ::GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SISO639LANGNAME2, szLang, 9) > 0)
	{
		wstring dll (L"console_");
		dll += szLang;
		dll += L".dll";
		hResources = ::LoadLibraryEx(dll.c_str(), NULL, LOAD_LIBRARY_AS_DATAFILE);

		Win32Exception ex("LoadLibraryEx", ::GetLastError());
		TRACE(L"LOCALE_SYSTEM_DEFAULT LOCALE_SISO639LANGNAME2=%s dll=%s hResources=%p (%S)\n", szLang, dll.c_str(), hResources, ex.what());
	}

	if(hResources)
	{
		_Module.SetResourceInstance(hResources);
	}
}
    subordinate_certificate_authority::~subordinate_certificate_authority()
    {
        // Bind the delete_subordinate_certificate_authority symbol dynamically and invoke it.
        typedef void (*function_type)(certificate_authority_type*);
        typedef boost::function<void(function_type)> deleter_type;

        hpx::util::plugin::dll dll(
            HPX_MAKE_DLL_STRING(std::string("security")));
        std::pair<function_type, deleter_type> function =
            dll.get<function_type, deleter_type>(
                "delete_subordinate_certificate_authority");

        (*function.first)(subordinate_certificate_authority_);
    }
Beispiel #10
0
bool Environment::Is64BitOperatingSystem() {
#if UCFG_64
	return true;
#elif UCFG_USE_POSIX
	return GetMachineType().find("X86_64") != String::npos;
#elif UCFG_WIN32_FULL
	typedef void (__stdcall *PFN)(SYSTEM_INFO *psi);
	CDynamicLibrary dll("kernel32.dll");
	if (PFN pfn = (PFN)GetProcAddress(dll.m_hModule, String("GetNativeSystemInfo"))) {
		SYSTEM_INFO si;
		pfn(&si);
		return si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64;
	}
#endif
	return false;
}
    void subordinate_certificate_authority::initialize()
    {
        // Bind the new_subordinate_certificate_authority symbol dynamically and invoke it.
        typedef certificate_authority_type* (*function_type)(
            components::security::key_pair const&);
        typedef boost::function<void(function_type)> deleter_type;

        hpx::util::plugin::dll dll(
            HPX_MAKE_DLL_STRING(std::string("security")));
        std::pair<function_type, deleter_type> function =
            dll.get<function_type, deleter_type>(
                "new_subordinate_certificate_authority");

        HPX_ASSERT(0 == subordinate_certificate_authority_);
        subordinate_certificate_authority_ = (*function.first)(key_pair_);
    }
Beispiel #12
0
    int StartHost()
    {
        string runtimePath(EnvironmentUtils::Get("KR_RUNTIME"));
        string dll(FileUtils::Join(runtimePath.c_str(), "khost.dll", 0));
        HMODULE khost = SafeLoadRuntimeDLL(dll);
        if (!khost)
            return __LINE__;

        Executor *executor = (Executor*) GetProcAddress(khost, "Execute");
        if (!executor)
        {
            ShowError(string("Invalid entry point 'Execute' in khost.dll"));
            return __LINE__;
        }

        return executor(::GetModuleHandle(NULL), argc, (const char**)argv);
    }
Beispiel #13
0
	void Debugger::loadDllEvent(const LOAD_DLL_DEBUG_INFO & loadDll)
	{
		//DLL housekeeping
		MODULEINFO modinfo;
		memset(&modinfo, 0, sizeof(MODULEINFO));
		GetModuleInformation(_process->hProcess,
			(HMODULE)loadDll.lpBaseOfDll,
			&modinfo,
			sizeof(MODULEINFO));
		DllInfo dll(loadDll.lpBaseOfDll, modinfo.SizeOfImage, modinfo.EntryPoint);
		_process->dlls.insert({ Range(dll.lpBaseOfDll, dll.lpBaseOfDll + dll.sizeOfImage - 1), dll });

		//call the debug event callback
		cbLoadDllEvent(loadDll, dll);

		//close the file handle
		CloseHandle(loadDll.hFile);
	}
Beispiel #14
0
bool wxIsDebuggerRunning()
{
#if wxUSE_DYNLIB_CLASS
    // IsDebuggerPresent() is not available under Win95, so load it dynamically
    wxDynamicLibrary dll(_T("kernel32.dll"), wxDL_VERBATIM);

    typedef BOOL (WINAPI *IsDebuggerPresent_t)();
    if ( !dll.HasSymbol(_T("IsDebuggerPresent")) )
    {
        // no way to know, assume no
        return false;
    }

    return (*(IsDebuggerPresent_t)dll.GetSymbol(_T("IsDebuggerPresent")))() != 0;
#else
    return false;
#endif
}
Beispiel #15
0
extern bool wxEnableFileNameAutoComplete(HWND hwnd)
{
#if wxUSE_DYNLIB_CLASS
    typedef HRESULT (WINAPI *SHAutoComplete_t)(HWND, DWORD);

    static SHAutoComplete_t s_pfnSHAutoComplete = NULL;
    static bool s_initialized = false;

    if ( !s_initialized )
    {
        s_initialized = true;

        wxLogNull nolog;
        wxDynamicLibrary dll(wxT("shlwapi.dll"));
        if ( dll.IsLoaded() )
        {
            s_pfnSHAutoComplete =
                (SHAutoComplete_t)dll.GetSymbol(wxT("SHAutoComplete"));
            if ( s_pfnSHAutoComplete )
            {
                // won't be unloaded until the process termination, no big deal
                dll.Detach();
            }
        }
    }

    if ( !s_pfnSHAutoComplete )
        return false;

    HRESULT hr = s_pfnSHAutoComplete(hwnd, 0x10 /* SHACF_FILESYS_ONLY */);
    if ( FAILED(hr) )
    {
        wxLogApiError(wxT("SHAutoComplete"), hr);
        return false;
    }

    return true;
#else
    wxUnusedVar(hwnd);
    return false;
#endif // wxUSE_DYNLIB_CLASS/!wxUSE_DYNLIB_CLASS
}
    void subordinate_certificate_authority::set_certificate(
        components::security::signed_certificate const & signed_certificate)
    {
        HPX_ASSERT(0 != subordinate_certificate_authority_);

        // Bind the subordinate_certificate_authority_set_certificate symbol dynamically and invoke it.
        typedef void (*function_type)(
            components::security::server::subordinate_certificate_authority*
          , components::security::signed_certificate const &);

        typedef boost::function<void(function_type)> deleter_type;

        hpx::util::plugin::dll dll(
            HPX_MAKE_DLL_STRING(std::string("security")));
        std::pair<function_type, deleter_type> function =
            dll.get<function_type, deleter_type>(
                "subordinate_certificate_authority_set_certificate");

        (*function.first)(
            subordinate_certificate_authority_, signed_certificate);
    }
    bool subordinate_certificate_authority::is_valid() const
    {
        HPX_ASSERT(0 != subordinate_certificate_authority_);

        // Bind the certificate_authority_is_valid symbol dynamically and invoke it.
        typedef void (*function_type)(
            components::security::server::certificate_authority_base*
          , bool*);

        typedef boost::function<void(function_type)> deleter_type;

        hpx::util::plugin::dll dll(
            HPX_MAKE_DLL_STRING(std::string("security")));
        std::pair<function_type, deleter_type> function =
            dll.get<function_type, deleter_type>(
                "certificate_authority_is_valid");

        bool valid;

        (*function.first)(subordinate_certificate_authority_, &valid);

        return valid;
    }
Beispiel #18
0
  void Init()
  {
    cDLL dll(TEXT("user32.dll"));
    if (dll.IsValid()) {
      BOOL (WINAPI *SetProcessDPIAware)() = nullptr;
      if (dll.LoadFunction("SetProcessDPIAware", &SetProcessDPIAware)) {
        std::wcout<<TEXT("WinMain Calling SetProcessDPIAware()")<<std::endl;
        SetProcessDPIAware();
      }
    }

    // Init common controls for modern looking theming
    INITCOMMONCONTROLSEX icce;
    icce.dwSize = sizeof(INITCOMMONCONTROLSEX);
    icce.dwICC =
      ICC_USEREX_CLASSES | // Combobox
      ICC_STANDARD_CLASSES // All other controls
    ;
    ::InitCommonControlsEx(&icce);

    // Init GDI+
    Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    Gdiplus::GdiplusStartup(&gGDIPlusToken, &gdiplusStartupInput, NULL);
  }
Beispiel #19
0
/* static */
wxRendererNative *wxRendererNative::Load(const wxString& name)
{
    wxString fullname = wxDynamicLibrary::CanonicalizePluginName(name);

    wxDynamicLibrary dll(fullname);
    if ( !dll.IsLoaded() )
        return NULL;

    // each theme DLL must export a wxCreateRenderer() function with this
    // signature
    typedef wxRendererNative *(*wxCreateRenderer_t)();

    wxDYNLIB_FUNCTION(wxCreateRenderer_t, wxCreateRenderer, dll);
    if ( !pfnwxCreateRenderer )
        return NULL;

    // create a renderer object
    wxRendererNative *renderer = (*pfnwxCreateRenderer)();
    if ( !renderer )
        return NULL;

    // check that its version is compatible with ours
    wxRendererVersion ver = renderer->GetVersion();
    if ( !wxRendererVersion::IsCompatible(ver) )
    {
        wxLogError(_("Renderer \"%s\" has incompatible version %d.%d and couldn't be loaded."),
                   name.c_str(), ver.version, ver.age);
        delete renderer;

        return NULL;
    }

    // finally wrap the renderer in an object which will delete it and unload
    // the library when it is deleted and return it to the caller
    return new wxRendererFromDynLib(dll, renderer);
}
Beispiel #20
0
/*
 * 功能:静态初始化设置
 * 编写:Rocky 2009-09-23 14:14:55
 * 返回:正确返回>=0值,出错返<0值;
 */
int Page::init()
{
    FUNCTION_TRACK(); // 函数轨迹跟踪


    int ret;
    static Page page;
    page.m_bParent = true;

    Page *obj = Page::instance( &page );
    if(NULL == obj)
    {
        LOG_ERROR("Page::instance() error");
        return ERR;
    }


    // 动态库文件目录
    const string &path = GlobalConfig::instance()->CgiDir();

    // 取出目录下所有动态库
    GetFileList dll( path );

    GetFileList::file_iterator file(dll);

    // 注册处理页面到队列
    while( file.next() )
    {
        DllLoad::Ptr dll;

        // 打开动态库
        if( dll->Open(file.name()) < 0 )
        {
            LOG_ERROR("加载动态库出错:[%s]", file.name());
            continue;
        }

        typedef void (*FuncPtr)(void *);

        // 取执行对象
        const string sym = "DllEnter";
        FuncPtr pSym = (FuncPtr)dll->GetSymbol(sym);
        if(NULL == pSym)
        {
            LOG_ERROR("取执行对象出错:[%s]", sym.c_str());
            continue;
        }

        // 执行(传入当前进程环境,即主模块的信息)
        (*pSym)( Environment::instance() );

        LOG_INFO("Loaded: [%s]", file.name());
    }

    // 初始化
    Factory::iterator it;

    for(it = Page::instance()->m_Factory.begin(); Page::instance()->m_Factory.end()!= it; it++)
    {
        const string &name = it->first;
        Page *&page = it->second;
        int ret = page->DoInit();
        if( ret < 0 )
        {
            LOG_ERROR("page->DoInit() error, name=[%s]", name.c_str());
            Page::instance()->UnRegister( name );
            continue;
        }
        LOG_DEBUG("Init page obj[%s] OK", name.c_str());
    }


    return OK;
}
Beispiel #21
0
// -----------------------------------------------------------------------------
// CEcmtPanPlugin::SendCurrentValues
// 
// -----------------------------------------------------------------------------
//
void CEcmtPanPlugin::SendCurrentValuesL( )
    {
#ifdef ECMT_RDEBUG
	RDebug::Print( _L( "EcmtPanPlugin::SendCurrentValuesL" ) );
#endif
    TBuf<KMaxWin32Path> buf;
    TBuf8<KMaxPanMsgLen> msg;
	TPtrC8 line;
	TLex8 lexer;
	
	/*
	* Handle bt.esk
	*/
    GetBtEskFilename( buf );
    
    REcmtFile btFile( buf );
    btFile.Read();
    if ( !btFile.IsGood() )
        {
        return;
        }

    line.Set( btFile.FindLine( KBtPort ) );
    if ( line.Length() == 0 )
        {
        return;
        }

    msg.Append( KBtCom );
    msg.Append( ' ' );

    lexer.Assign( line );
    lexer.SkipCharacters();
    msg.Append( lexer.NextToken() );
    msg.Append( ' ' );
    
    line.Set( btFile.FindLine( KHciDll ) );
    if ( line.Length() == 0 )
        {
        return;
        }

    msg.Append( KHci );
    msg.Append( ' ' );
    lexer.Assign( line );
    lexer.SkipCharacters();
    TPtrC8 dll( lexer.NextToken() );
    if ( dll.CompareF( KHciDllBcsp ) == 0 )
        {
        msg.Append( '0' );
        }
    else if ( dll.CompareF( KHciDllH4 ) == 0 )
        {
        msg.Append( '1' );
        }
    else if ( dll.CompareF( KHciDllUsb ) == 0 )
        {
        msg.Append( '2' );
        }
    else
        {
        msg.Append( '-1' );
        }

	/*
	* Handle irda.esk
	*/
    GetIrdaEskFilename( buf );
    
    REcmtFile irdaFile( buf );
    irdaFile.Read();
    if ( !irdaFile.IsGood() )
        {
        return;
        }

    line.Set( irdaFile.FindLine( KIrdaPort ) );
    if ( line.Length() == 0 )
        {
        return;
        }

    msg.Append( ' ' );
    msg.Append( KIrdaCom );
    msg.Append( ' ' );

    lexer.Assign( line );
    lexer.SkipCharacters();
    msg.Append( lexer.NextToken() );

	/*
	* Send values
	*/
    CEcmtMessageEvent* m = iMessaging->NewMessageEvent( iTargetUid, msg );
    if ( m )
        {
#ifdef ECMT_RDEBUG
		RDebug::Print( _L( "EcmtPanPlugin::SendCurrentValuesL: Sending a message" ) );
#endif
        iMessageSender->SendMessage( m );
        }
    }
Beispiel #22
0
void UnitTest::TestGeohash_QueryByRadius()
{
    const uint8_t bitDepth = 52;
    const uint32_t pntCount = 1e6;
    vector<pair<double,double> > pnts;
    /*
     * Filling random point data to emulate points on the ground
    */
    preparePointData(pnts, llRange, pntCount);
    cout << pntCount << " points are ready" << endl;
    //my centos 6 equips with g++4.4.7 that doesn't support c++11
    //for(auto p:pnts)centerHash
    //for(auto p = pnts.begin(); p != pnts.end(); ++p)
    //    cout << (*p).first <<"," << p->second <<endl;

    /*
     * First, let's geohash all points and save them in a Set so we can conduct binary search later
     * with guaranteed O(logN)
     * Default bit depth is 52
    */
    set<uint64_t> container;
    for(auto p = pnts.begin(); p != pnts.end(); ++p)
        container.insert(naiveEncodeGeohash(p->first, p->second, bitDepth));
    cout << "Point data have been geohashed" << endl;

    /*
     * Search POI surrounding my location:
     *
     * Set up the lat/lon as the center for search and of course, the radius
     *
    */
    double radius = 1e5;
    double centerLon = 0.0;
    double centerLat = 0.0;
    /*
     * First let's get the number of bits that are necessary to represent this central lon/lat based upon radius.
     * In other word, at this particular bit depth level, this raduis is recognizable (has sufficient resolution)
     * , which means the cell at this bit depth level is greater than the radius.
    */
    uint8_t estBitDepth = guessNumberOfBits(radius, centerLat);
    uint64_t min = 0ULL, max = 0ULL;
    /*
     * Encode central lon/lat
    */
    uint64_t centerHash = naiveEncodeGeohash(centerLon, centerLat, estBitDepth);
    /*
     * According to the hash value at estimated bit depth level, find out what are the corresponding min, max values at level 52.
     * In other words, with this cell size (at estimated bit-depth level), how many cells at bit-depth level 52 should be covered.
    */
    naiveCellMaxMin(centerHash, estBitDepth, &min, &max, bitDepth);
    /*
     * Define search ranges
    */
    vector<pair<uint64_t, uint64_t> > ranges;
    ranges.push_back(std::make_pair(min, max));
    GH_DIRECTION dirs[]{GH_DIRECTION::NORTH, GH_DIRECTION::EAST, GH_DIRECTION::NORTHEAST, GH_DIRECTION::NORTHWEST, GH_DIRECTION::SOUTH, GH_DIRECTION::SOUTHEAST, GH_DIRECTION::SOUTHWEST, GH_DIRECTION::WEST};
    uint64_t neighborHash = 0ULL;
    /*
     * Put all neighbors in, be awared: we didn't try to optimize this by merging overlapping ranges or removing duplicates or invalid,
     * which should be done in a real world app.
     */
    for(int i = 0; i < 8; ++i)
    {
        neighborHash = naiveNeighbor(centerHash, estBitDepth, dirs[i]);
        naiveCellMaxMin(neighborHash, estBitDepth, &min, &max, bitDepth);
        ranges.push_back(std::make_pair(min, max));
    }
    set<uint64_t>::iterator low;
    uint32_t count = 0;
    Envelope dll(0, 0, 0, 0);
    /*
     * Use a set to hold the hits through geohash-based query in order to avoid any duplicates
    */
    set<uint64_t> result;
    for(int i = 0; i < 9; ++i)
    {
        /*
         * This lower bound value is the starting point, if its value is no greater than ranges[i].second,
         * we consider all values in between [low, ranges[i].second) as candidates.
         * Then, we will have to scan all of them to get rid of false candidates.
        */
        low = container.lower_bound(ranges[i].first);
        for(auto itor = low; *itor < ranges[i].second; ++itor)
        {
            dll = naiveDecodeGeohash(*itor, bitDepth);
            /*
             * Haversine distance
             * We decode hash into an envelope and then use the center of this envelop to calcuate the distance to the central point
            */
            if(lonlatDistHaversine(centerLon, centerLat, (dll.xmax + dll.xmin)/2.0, (dll.ymax + dll.ymin)/2.0) <= radius)
                result.insert(*itor);
        }
    }
    cout << "Geohash found " << result.size() << " hits!"<<endl;
    /*
     * Verify the correctness of geohash based query by comparing the number of hits with a brute-force linear scanning against entire
     * dataset.
    */
    for(auto itor = container.begin(); itor != container.end(); ++itor)
    {
        dll = naiveDecodeGeohash(*itor, bitDepth);
        if(lonlatDistHaversine(centerLon, centerLat, (dll.xmax + dll.xmin)/2.0, (dll.ymax + dll.ymin)/2.0) <= radius)
            ++count;
    }
    cout << "Linear scan found " << count << " hits!"<< endl;
    QCOMPARE(count, (uint32_t)result.size());
}
Beispiel #23
0
void process()
{
    std::cout << "process()!!" << std::endl;
    std::string dll("test.dll");
    processThroughMono(dll);
}