【问题标题】:P/Invoke code works on WinXP, exception on Win2k8P/Invoke 代码在 WinXP 上工作,在 Win2k8 上异常
【发布时间】:2011-03-09 23:37:23
【问题描述】:

我正在尝试使用 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#,因为我还不太熟悉那种语言。

任何建议将不胜感激。

【问题讨论】:

  • 作为参考,stackoverflow.com/questions/3146017/… 接受的答案是我正在尝试实现的。
  • GetAddress 和 GetRegistrationAddress 不是同一个函数。你有正在执行的实际代码吗?
  • 干杯。显然,它也应该是 GetAddress 那里。我已经解决了。上面的摘录是复制粘贴的代码,我也添加了C#调用sn-p。

标签: c# c++ dll pinvoke


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2012-11-07
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    相关资源
    最近更新 更多