代码之家  ›  专栏  ›  技术社区  ›  dlanod

P/Invoke代码在WinXP上工作,在Win2k8上异常

  •  1
  • dlanod  · 技术社区  · 15 年前

    我试图在C语言和C++中访问一个DLL中的函数。

    C++工作得很好,就像WiXP上的C语言一样。但是,在尝试访问Win2k8系统上的函数时,出现以下错误:

    Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory
    is corrupt.
       at Router.GetAddress()
    

        [DllImport("Constants.dll")]
        static extern String GetAddress();
    

    C#(目前)中的用法只是输出它:

    Console.WriteLine(GetAddress());
    

    const static WCHAR* szAddress= L"net.tcp://localhost:4502/TestAddress";
    
    extern "C" __declspec(dllexport) const WCHAR* GetAddress()
    {
         return szAddress;
    }
    

    如有任何建议,将不胜感激。

    1 回复  |  直到 15 年前
        1
  •  0
  •   dlanod    15 年前

    我最终用中的细节解决了这个问题 http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/4e387bb3-6b99-4b9d-91bb-9ec00c47e3a4 .

        [DllImport("Constants.dll", CharSet = CharSet.Unicode)]
        static extern int GetAddress(StringBuilder strAddress); 
    

    因此,用法变为:

    StringBuilder sb = new StringBuilder(1000000); // Arbitrary length for the time being
    GetAddress(sb);
    Console.WriteLine(sb.ToString());
    

    DLL更改为:

    const static WCHAR* szAddress = L"net.tcp://localhost:4502/TestAddress";
    
    extern "C" __declspec(dllexport) int GetAddress(WCHAR* strAddress)
    {
         wcscpy(strAddress, szAddress);
         return 0;
    }