tags:

views:

46

answers:

1

I'm attempting to access a function in a DLL in C# and C++.

C++ is working fine, as is C# on WinXP. However I'm getting the following error when attempting to access the function on a Win2k8 system:

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

The declaration in C# is:

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

Usage in C# (at the moment) is just outputting it:

Console.WriteLine(GetAddress());

And the contents of the DLL's function are just:

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

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

I really didn't think there was anything controversial here. The only thing I can think of is the const return from GetAddress, but I'm not sure how to apply the corresponding keyword to C# as I'm not as familiar with that language yet.

Any suggestions would be greatly appreciated.

A: 

I ended up fixing this problem using the details in http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/4e387bb3-6b99-4b9d-91bb-9ec00c47e3a4.

I changed the declaration to:

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

The usage therefore became:

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

And the DLL was changed to:

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

extern "C" __declspec(dllexport) int GetAddress(WCHAR* strAddress)
{
     wcscpy(strAddress, szAddress);
     return 0;
}
dlanod