【问题标题】:DllImport C# to C++ with Memory Access ViolationDllImport C# to C++ with Memory Access Violation
【发布时间】:2014-02-21 16:28:35
【问题描述】:

我有一个 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);

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

有人知道如何处理这个错误吗?

【问题讨论】:

  • 又一个缺少 CallingConvention.Cdecl 的案例
  • 对不起朋友,但不工作,现在在函数的开头抛出异常。
  • CarregadorFotos.exe 中发生了“System.AccessViolationException”类型的未处理异常附加信息:试图读取或写入受保护的内存。这通常表明其他内存已损坏。线程“Win32 线程”(0x738) 已退出,代码为 0 (0x0)。

标签: c# c++ dllimport extern


【解决方案1】:

你的 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 否则您可能会遇到“不平衡堆栈”异常

【讨论】:

  • [DllImport(@"UrmTest.dll", CallingConvention = CallingConvention.Cdecl)] static extern int wmain([MarshalAs(UnmanagedType.LPStr)]string config, [MarshalAs(UnmanagedType.LPStr)]string小路);不工作,另一个不工作。同样的错误。
  • 在将 char 转换为 _bstr_t 时,有时会在 xstring 中出现错误
  • 所以也许这不是编组错误。您的 C++ 代码中可能存在错误。
  • 好的,谢谢,我有这个转换 _bstr_t config(configr);将其配置为 char*。在此转换之前仅此而已。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 1970-01-01
  • 2023-03-30
  • 2022-12-26
  • 2022-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多