c# - P/Invoke 代码在 WinXP 上工作,在 Win2k8 上异常(exception)

标签 c# c++ dll pinvoke

我正在尝试访问 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/

相关文章:

c# - GNUPG:在删除公钥时抑制消息

c++ - 模板和接口(interface)的多重继承问题

c++ - 编写一个函数的原型(prototype),该函数需要一个正好是 16 个整数的数组

c++ - mbed:使用 USBDevice 库编译导致错误

visual-c++ - 什么是 .sym 文件以及如何从 Visual-C++ 使用它?

c# - C# 运行时导入失败中的 C++ 非托管 DLL

c# - 相当于库 (DLL) 的 'app.config'

c# - 读取复杂的 XML 属性

c# - 如何在每个配置的基础上添加程序集引用

c# - 即使封装在 using() 中,内存流也不可扩展