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.

dlanod
  • 8,664
  • 8
  • 54
  • 96
  • For reference's sake, the accepted answer at http://stackoverflow.com/questions/3146017/how-do-i-share-a-constant-between-c-and-c-code is what I'm attempting to implement. – dlanod Jun 30 '10 at 06:38
  • 1
    GetAddress and GetRegistrationAddress are not the same function. Do you have the actual code that's being executed? – Windows programmer Jun 30 '10 at 06:54
  • Cheers. It was meant to be GetAddress there as well obviously. I've fixed that up. The excerpts above are copied and pasted code, and I've added the C# calling snippet as well. – dlanod Jun 30 '10 at 22:24

1 Answers1

0

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
  • 8,664
  • 8
  • 54
  • 96