title: How can i get an object from pointer-address
body: <p>i have written a user control for WinCC (Siemens) (SCADA). Now I want to pass a pointer to the control. The only way to do this is: write the pointer to a property.</p>
  
  <p>WinCC has only this methods to set properties</p>
  
  <ul>
  <li>SetPropBOOL</li>
  <li>SetPropChar</li>
  <li>SetPropDouble</li>
  <li>SetPropWord</li>
  </ul>
  
  <p>The property from control has UInt as datatype and i use the SetPropDouble method to set the address from an object.</p>
  
  <p><strong>WinCC Global Script (ANSI-C)</strong></p>
  
  <pre><code>//autoDB is an ADODB.Connection object
  //object* autoDB = __object_create("ADODB.Connection");
  extern __object* autoDB;
  //SetPropDouble( "PictureName", "ControlName", "PropertyName", (DWORD)(&amp;autoDB) );
  SetPropDouble( "PictureName", "ControlName", "PropertyName", (DWORD)autoDB );
  </code></pre>
  
  <p>I've debug my control (hook on WinCC-process) and i see the property-set becomes assigned an address-value e.g. 0x03041080.</p>
  
  <p><strong>Now the question: How can i get the object in c# (.Net) on the address?</strong></p>
  
  <p>My try throws an exception: <strong>ExecutionEngineException</strong></p>
  
  <pre><code>private ADODB.Connection _database;
  private IntPtr _ptr = IntPtr.Zero;
  
  public uint DataBase{
      get{
          return (uint)_ptr;
      }
      set{
          if( value != 0 ){
              _ptr = (IntPtr)value;
              GCHandle gH = GCHandle.FromIntPtr(_ptr); // THIS LINE THROW THE EXCEPTION
              _database = gH.Target;
          }
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>Ok: i've changed my code to use <code>STRING</code></h2>
  
  <p><strong>WinCC</strong></p>
  
  <pre><code>extern __object* autoDB;
  DWORD addr = (DWORD)autoDB;
  char sAddr[11];
  sprintf( sAddr, "%d\0", addr );
  SetPropChar( "PictureName", "ControlName", "DataBaseAddr", sAddr );
  </code></pre>
  
  <p>And c# is now</p>
  
  <pre><code>private string _lpszDataBaseAddr = "";
  public string DataBaseAddr{
      get{
          return _lpszDataBaseAddr;
      }
      set{
          uint addr;
          bool ret = uint.TryParse( value, out addr );
          if( ! ret ){
              return;
          }
          IntPtr ptr = (IntPtr)addr;
          GCHandle gH = GCHandle.FromIntPtr( ptr );  // THE SAME ERROR!
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>Other findings!</h2>
  
  <p>The address from the ADO-Object is not in the process-memory who called my control (debug with ollydbg). WinCC has two programs: PDLRT.exe for visualisation (this is calling my control) and SCRIPT.exe for running GLOBAL-SCRIPT (Ansi-C).</p>
  
  <p>From PDLRT, i've access to the pointer-address from ADO-Object. By call GCHandle in C# of the ADO-object-address, the exception is thrown. (<strong>ExecutionEngineException</strong>)</p>