我正在尝试访问 C# 和 C++ 中的 DLL 中的函数。
C++ 工作正常,C# 在 WinXP 上也是如此。但是,当我尝试在 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#,因为我还不太熟悉该语言。
如有任何建议,我们将不胜感激。
最佳答案
我最终使用 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;
}
关于c# - P/Invoke 代码在 WinXP 上工作,在 Win2k8 上异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3146948/