将c#字符串传递给非托管c ++ DLL

时间:2010-03-04 15:47:52

标签: .net clr unmanaged marshalling

我有一个简单的应用程序,它加载一个非托管的dll,并从C#传递一些字符串值。但是在C ++ DLL应用程序中,我收到一个异常::尝试访问读/写保护的内存。我的DLL导入如下所示:

[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);

和C ++声明就像

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

请帮助!!!

2 个答案:

答案 0 :(得分:7)

string != LPStr

尝试:

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

}

答案 1 :(得分:2)

我会修改pinvoke签名....

[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);

然后将sbProcNamesbMessage传递给DumpToDBLogFile ......

希望这有帮助, 最好的祝福, 汤姆。