我有一个从 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.lib
和 TrackerWrapper.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"
更改为相对路径和绝对路径,但我遇到了同样的问题。
有什么想法吗?
最佳答案
您可以尝试两件事:
- 检查 FileNotFoundException 中是否有内部异常,如果有, 它可能会为您提供详细信息。
- 使用 process monitor 监控流程从系统内部,它可以记录进程的所有文件事件,从日志中,您可以知道丢失了哪个文件。请记住将过滤器设置为仅监控您的进程,否则它将监控所有进程。
关于c# - 文件未找到异常 : Could not load file or assembly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24414528/