我有一個從C#編譯的dll(Tracker.dll
),需要在本機C++中使用它。我解決了這個問題;由於我無法修改C#,因此我正在編寫託管C++包裝並相應地導出類。對於一個(簡化的)例子:FileNotFoundException:無法加載文件或程序集
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"
以相對以及絕對路徑,但我得到同樣的問題。
任何想法?
你檢查了Tracker.dll的依賴嗎? – Matt
沒有典型的.NET依賴關係。 –