【问题标题】:Unable to write to files in C++ dll project under C# Windows Application无法在 C# Windows 应用程序下写入 C++ dll 项目中的文件
【发布时间】:2014-04-02 09:42:12
【问题描述】:

我有一个 C++ dll 项目,它将由 C# Windows 应用程序调用。但是每次我尝试写入C++ dll项目中的文件时,我都会得到以下错误:

An unhandled exception of type 'System.AccessViolationException' occurred in Wrapper.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

收到此错误时,代码指针指向文件fstream_Lock()

我在C++ dll项目中使用的代码是:

ofstream ofs("debug.txt");      // OK
if (ofs.good())                 // OK
    ofs << "aaa" << endl;       // this line causes the error  <--
ofs.close();

其他信息:

  1. 在VS2010-Winx64(.NET Framework 4)下开发。
  2. Wrapper 是托管 C++ 项目,它封装 C++ 代码以便在 C# 中调用。
  3. 我检查了debug.txt 文件,该文件是可写的。

非常感谢任何建议。谢谢。

【问题讨论】:

  • 检查您是否确实有权写入运行应用程序的文件夹。从字面上看可能是 Windows 访问问题或文件是只读的?
  • @miltonb 我更新了问题,谢谢。
  • 您正在传递一个需要指针的值...
  • @leppie 我不明白。我在哪里传递了一个值?
  • 到目前为止,AV 最常见的原因是堆损坏。它绝不是由触发异常的代码引起的。不必调试这样的 Heisenbugs 当然是托管代码流行的一个重要原因:)

标签: c# c++ visual-studio-2010 dll file-io


【解决方案1】:

原来我在设置运行时库时搞混了。将 C++ dll 项目的运行时库从 /MD 更改为 /MDb 解决了该问题。

在 VS2010 中,可以这样做:

Project -> Properties -> Configuration Properties -> C/C++ 
        -> Code Generation -> Runtime Library -> Multi-threaded Debug DLL (/MDd)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2016-12-12
    相关资源
    最近更新 更多