DllImport C#到C ++与内存访问冲突

时间:2014-01-29 17:32:01

标签: c# c++ dllimport extern

我有一个dllimport的问题,首先是C ++代码:

   extern "C" {
   __declspec(dllexport) int wmain(char* configr, char* path)
   {
     ILoggerPtr logger;

   try
   {        
     _bstr_t config(configr);
     _bstr_t srcFile(path); 
   }

我的C#代码:

    [DllImport(@"Test.dll")]
    static extern int wmain(string config, string path);

对C ++的调用:

    string path = "c:\\bmp\\" + im.ID_MOVIMENTO + "_gray.bmp";
    temp.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
    int k = wmain("Brasil", path);

Oks,问题是,在C ++ char *到_bstr_t的第一次转换中有错误: CarregadorFotos.exe中发生未处理的“System.AccessViolationException”类型异常

有人有任何想法来管理这个错误吗?

1 个答案:

答案 0 :(得分:0)

您的C#签名应为:

  [DllImport(@"Test.dll")]
    static extern int wmain([MarshalAs(UnmanagedType.LPStr)]string config, 
[MarshalAs(UnmanagedType.LPStr)]string path);

  [DllImport(@"Test.dll")]
    static extern int wmain(IntPtr config,  IntPtr path);

正如Hans Passant所说,使用CallingConvention.Cdecl或者您可能会遇到“不平衡堆栈”异常