6

I have a simple application that loads an unmanaged dll and passes a few string values to it from C#. But in the C++ dll application, I receive an exception :: Tried to access a read/write protected memory. My DLL Import looks like this:

[DllImport("X.dll", CallingConvention = CallingConvention.Cdecl) ]
public static extern int
DumpToDBLogFile([MarshalAs(UnmanagedType.I4)]int loggingLevel,
                [MarshalAs(UnmanagedType.I4)]int jobId,
                int threadId,
                [MarshalAs(UnmanagedType.LPStr)]string procName,
                [MarshalAs(UnmanagedType.LPStr)]string message);

and the C++ Declaration is like

extern "C"    
__declspec(dllexport) int DumpToDBLogFile( int loggingLevel, int jobId, int threadId, string procName, string message )
{
    //access strings..
}

Help please!!!

Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79
Prabhu
  • 3,434
  • 8
  • 40
  • 48

2 Answers2

7
string != LPStr

try:

extern "C"
__declspec(dllexport) int DumpToDBLogFile( int loggingLevel, int jobId, int threadId, char* procName, char* message ) { //access strings..

}
Andrey
  • 59,039
  • 12
  • 119
  • 163
  • This is correct. Change the declaration of the function on the C++ side to accept a raw char* instead of an std::string. –  Mar 04 '10 at 15:59
  • I changed the declaration to char* and it worked. But should i deallocate the char* from c++ once I'm done. If i don't wouldnt that result in memory leak..?? – Prabhu Mar 05 '10 at 06:46
  • Thank you so much guys. I have struggled with this problem for a very long time. :( – DynamicScope Jul 15 '11 at 06:10
2

I would modify the pinvoke signature....

[DllImport("X.dll", CallingConvention = CallingConvention.Cdecl) ]
public static extern int
DumpToDBLogFile(int loggingLevel, int jobId, int threadId, StringBuilder procName, StringBuilder message);

And from the managed side use the StringBuilder class initialized....

StringBuilder sbProcName = new StringBuilder(1024);
StringBuilder sbMessage = new StringBuilder(1024);

Then pass in the sbProcName and sbMessage to the DumpToDBLogFile...

Hope this helps, Best regards, Tom.

t0mm13b
  • 34,087
  • 8
  • 78
  • 110