Passing a C # string to an unmanaged C ++ library

I have a simple application that loads an unmanaged dll and passes it some string values ​​from C #. But in a C ++ dll application, I get a :: Tried exception to access protected read / write 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 me please!!!

+5
source share
2 answers
string != LPStr

to try:

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

}
+7
source

I would change the pinvoke signature ....

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

StringBuilder, ....

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

sbProcName sbMessage DumpToDBLogFile...

, , , .

+2

All Articles