2014-06-27 80 views
2

我想將非託管C++庫鏈接到C#應用程序。我正在使用PInvoke進程,因爲非託管C++ dll具有多個不能用CLR編譯的依賴項。當我編譯下面的示例代碼時,出現以下錯誤。我找到了一個需要添加dll參考的參考,但MSVS告訴我它不能添加它。我也讀過關於使用regsvr32註冊它,但這似乎是特定於CLR庫,對吧?所以我的問題是,我如何清除這個錯誤的非託管DLL?如何在C#中定義非託管dll依賴關係

ServerTerminal.cs(62,48): error CS1031: Type expected 
ServerTerminal.cs(62,48): error CS1519: Invalid token ';' in class, struct, or interface member declaration 
ServerTerminal.cs(64,48): error CS1031: Type expected 
ServerTerminal.cs(64,48): error CS1519: Invalid token ';' in class, struct, or interface member declaration 

ServerTerminal.cs: 
    class ServerTerminal 
    { 
     private delegate int Callback(string text); 
     private Callback mInstance; 

     public ServerTerminal() 
     { 
      mInstance = new Callback(Handler); 
      SetCallback(mInstance); 
     } 

     public void Test() 
     { 
      TestCallback(); 
     } 

     private int Handler(string text) 
     { 
      return 0; 
     } 
     [DllImport(@"..\\lib\\DDS_Service.dll", EntryPoint="SetCallback")]; 
     private static extern void SetCallback(Callback fn); 
     [DllImport(@"..\\lib\\DDS_Service.dll", EntryPoint="TestCallback")]; 
     private static extern void TestCallback(); 
    } 

和C++ DLL的Component.h:

typedef int (__stdcall * Callback)(const char* text); 
Callback Handler=0; 
class COM_Component : public CM_Component 
{ 
    // Contents not pasted 
} 

和C++ DLL的Component.cpp:

extern "C" __declspec(dllexport) 
void __stdcall SetCallback(Callback handler) 
{ 
    Handler = handler; 
} 

extern "C" __declspec(dllexport) 
void __stdcall TestCallback() 
{ 
    int retval = Handler("hello world"); 
} 

COM_Component::COM_Component(void) : CM_Component(TDstring("COM_Component")) 
{ 
    // register the observer callback methods 
} 
// Remainder of file not pasted 
+0

具體來說,當我嘗試將DLL引用映射到C#項目時,出現的錯誤是:「無法添加對dll的引用。請確保該文件是可訪問的,並且它是有效的程序集或COM組件「。 –

+0

刪除屬性 – erikkallen

回答

2

您的「無效標記」編譯器錯誤是由於緊接在DllImport屬性之後的分號造成的。另外,你需要在其中指定一個帶有雙反斜槓的逐字@ @「...」字符串。我覺得你的聲明應該是這樣的:

[DllImport(@"..\lib\DDS_Service.dll", EntryPoint="SetCallback")] 
    private static extern void SetCallback(Callback fn); 

如果你的DLL是一個COM DLL,那麼你就可以運行Regsvr32註冊它,在你的項目中添加對它的引用。如果是這樣的話,那麼你不需要使用P/Invoke:你可以像任何其他庫一樣引用它。

+0

後面的分號啊,就是這樣 - 謝謝! –

2
[DllImport(@"..\\lib\\DDS_Service.dll", EntryPoint="SetCallback")]; 
private static extern void SetCallback(Callback fn); 
[DllImport(@"..\\lib\\DDS_Service.dll", EntryPoint="TestCallback")]; 
private static extern void TestCallback(); 

祛瘀在DllImport屬性之後的行中的;