c# - 文件未找到异常 : Could not load file or assembly

标签 c# c++ visual-studio-2012 dll

我有一个从 C# 编译的 dll (Tracker.dll),需要在 native C++ 中使用它。我已经解决了这个问题;因为我不能修改 C#,所以我正在编写一个托管的 C++ 包装器并相应地导出类。对于一个(简化的)示例:

TrackerWrapper.h

#pragma once

#include <memory>

class __declspec(dllexport) TrackerWrapper {
  public:
    TrackerWrapper();
    ~TrackerWrapper();
    void Track();
  private:
    struct Impl;
    std::unique_ptr<Impl> pimpl;
};

TrackerWrapper.cpp

#using "Tracker.dll"

#include "TrackerWrapper.h"
#include <msclr\auto_gcroot.h>

using namespace System::Runtime::InteropServices;

struct TrackerWrapper::Impl {
  msclr::auto_gcroot<Tracker^> tracker;

  Impl() : tracker(gcnew Tracker()) {}
  ~Impl() {}
};

TrackerWrapper::TrackerWrapper() : pimpl(new Impl()) {}
TrackerWrapper::~TrackerWrapper() {}

void TrackerWrapper::Track() {
  pimpl->tracker->Track();
}

main.cpp

#include "TrackerWrapper.h"
int main() {
  TrackerWrapper tracker;
  tracker->Track();
  return 0;
}

只要所有的对象和二进制文件都在同一个目录中,编译后

cl /clr /LD TrackerWrapper.cpp
cl Main.cpp TrackerWrapper.lib,

一切都完美运行。但是,理想情况下,我们需要将 Tracker.dll 以及 TrackerWrapper.libTrackerWrapper.dll 放在单独的目录中,例如垃圾箱。

因此,目录结构可能如下所示:

bin\
  Tracker.dll
  TrackerWrapper.dll
  TrackerWrapper.lib
  <other objects>

Main.cpp
TrackerWrapper.h
TrackerWrapper.cpp

我可以通过将 bin 添加到我的 %PATH%%LIB%%LIBPATH%< 来编译所有内容 环境变量(或在编译时通过 /link/AI 在命令行上),但是当我执行生成的可执行文件时,出现以下错误:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Tracker, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
  at TrackerWrapper.Impl.{ctor}(Impl* )
  at TrackerWrapper.{ctor}(TrackerWrapper* )

我曾尝试将 #using "Tracker.dll" 更改为相对路径和绝对路径,但我遇到了同样的问题。

有什么想法吗?

最佳答案

您可以尝试两件事:

  1. 检查 FileNotFoundException 中是否有内部异常,如果有, 它可能会为您提供详细信息。
  2. 使用 process monitor 监控流程从系统内部,它可以记录进程的所有文件事件,从日志中,您可以知道丢失了哪个文件。请记住将过滤器设置为仅监控您的进程,否则它将监控所有进程。

关于c# - 文件未找到异常 : Could not load file or assembly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24414528/

相关文章:

c++ - VS2012加入VC2010编译器

c++ - 在带有 msvc11 的静态类析构函数中使用 std::system_category()

visual-studio-2012 - 如果构建后事件运行返回错误的程序,如何中止或失败 Visual Studio 构建

c# - 带虚线的 TreeView/TreeViewItem ControlTemplates

c# - RX + TPL + 测试

c# - Kim 和 Pearl 的贝叶斯网络中的消息传递算法

c++ - 为什么我的数组没有输出正确的数据,这些数据是从外部文件输入的?

c++ - 在 C++ 中摆脱非动态内存

c# - CanExecute RelayCommand MVVM Light 5+ 上的奇怪行为

c++ - 是否存在 difftime 计算闰秒的实际系统?