Passing c# string to unmanaged c++ DLL

2019-03-30 02:34发布

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!!!

2条回答
Ridiculous、
2楼-- · 2019-03-30 03:14
string != LPStr

try:

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

}
查看更多
放我归山
3楼-- · 2019-03-30 03:19

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.

查看更多
登录 后发表回答