P / Invoke代码适用于WinXP,Win2k8上的异常

时间:2010-06-30 06:38:19

标签: c# c++ dll pinvoke

我正在尝试使用C#和C ++访问DLL中的函数。

C ++工作正常,WinXP上的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()

C#中的声明是:

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

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

Console.WriteLine(GetAddress());

DLL函数的内容只是:

const static WCHAR* szAddress= L"net.tcp://localhost:4502/TestAddress";

extern "C" __declspec(dllexport) const WCHAR* GetAddress()
{
     return szAddress;
}

我真的不认为这里有什么争议。我唯一能想到的是来自GetAddress的const返回,但我不确定如何将相应的关键字应用于C#,因为我还不熟悉那种语言。

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我最终使用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;
}