2014-06-25 165 views
0

我有一個從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.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"以相對以及絕對路徑,但我得到同樣的問題。

任何想法?

+0

你檢查了Tracker.dll的依賴嗎? – Matt

+0

沒有典型的.NET依賴關係。 –

回答

0

您的庫由.net基礎結構加載,它只在應用程序目錄或GAC中默認搜索。

如果你的應用程序是.net,那麼你可以在App.config中指定一個庫路徑,但作爲你的應用程序是本地的不知道如果混合的DLL會加載App.config或不,可以嘗試。

MSDN

You can use the < probing > element in the application configuration file to specify subdirectories the runtime should search when locating an assembly.

如果不工作,然後你的最後一個選項是將庫添加到GAC,但庫會不會真的是在指定的文件夾,但複製到GAC的文件夾中。

1

有兩件事情可以嘗試:

  1. 檢查是否有在FileNotFoundException異常的內部異常,如果確實, 它可能給你的詳細信息。
  2. 從系統內部監視process monitor的進程,它可以記錄進程的所有文件活動,從日誌中可以知道哪個文件丟失。請記住將過濾器設置爲僅監視您的過程,否則將監視所有過程。
相關問題