title: Getting value of a char* exported by unmanaged dll in .NET
body: <p>Im trying to get a value of a string exported by an unmanaged dll.</p>
  
  <p>The string in the dll is declared as</p>
  
  <pre><code>extern "C" __declspec(dllexport) const char* _Version = "0.1";
  </code></pre>
  
  <p>The code I'm using to get the value is below. I get the address for the variable from the call to <code>GetProcAddress</code> but <code>Marshal.PtrToStringAuto</code> returns garbage...</p>
  
  <p>Whats wrong?</p>
  
  <pre><code>    public string GetDllVersion()
      {
              IntPtr lib = LoadLibrary(@"some.dll");
              if(lib == IntPtr.Zero)
                      throw new Win32Exception(Marshal.GetLastWin32Error());
  
              IntPtr procAddress = GetProcAddress(lib, "_Version");
              var ver2 = Marshal.PtrToStringAuto(procAddress);
  
              if(!FreeLibrary(lib))
                      throw new Win32Exception(Marshal.GetLastWin32Error());
              return ver2;
      }
  
      [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
      static extern IntPtr LoadLibrary(string lpFileName);
  
      [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
      static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
  
      [DllImport("kernel32.dll", SetLastError = true)]
      [return: MarshalAs(UnmanagedType.Bool)]
      static extern bool FreeLibrary(IntPtr hModule);
  </code></pre>