2014-07-13 40 views
1

當我嘗試爲一個非常簡單的COM服務器運行一個非常簡單的COM客戶端時,我收到各種錯誤,這是我在C++中編寫的。 COM服務器是用C++編寫的,只有一個方法「GetSomeString」。我內置的COM服務器的OCX,使用regsrv32註冊它,然後從下面的C#控制檯應用程序中引用它:無法運行一個非常簡單的COM客戶端

using MySimpleActivexControlLib; 

namespace SimpleConsoleApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var c = new MySimpleActivexControlLib.MySimpleActivexControl(); 
      c.GetSomeString(); 
     } 
    } 
} 

當我運行代碼,我得到以下異常:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

我試圖從一個C++控制檯應用程序使用該組件,並得到了另一個錯誤:

... Microsoft C++ exception: _com_error at memory location 0x002bf5e4 ...

完整的代碼可被視爲here。 任何幫助將不勝感激。

+1

您是否考慮過使用調試器來查看爲什麼會引發異常? –

+0

@RaymondChen感謝您的回覆。在C#控制檯中,一旦引發異常,這是運行堆棧的頂部: 1. mscorlib.dll!System.RuntimeType.ForwardCallToInvokeMember(string memberName,System.Reflection.BindingFlags標誌,對象目標,int [] aWrapperTypes, ref [System.Runtime.Remoting.Proxies.MessageData msgData)+ 0x183 bytes 2. [Native to Managed Transition] 3. [Managed to Native Transition] 4. SimpleConsoleApp.exe!SimpleConsoleApp.Program.Main(string [] args )第11行+ 0x9字節\t C# 編輯:抱歉的格式不對,我試圖格式化堆棧幀更加理智。 – JohnnyW

+0

我也嘗試在VirtualBox上運行Windows 7的全新安裝,然後安裝VS 2010(作爲唯一的軟件安裝),並且仍然出現相同的錯誤。 – JohnnyW

回答

3

這當然取決於ActiveX控件內部的內容,但是你沒有顯示任何代碼。

例如,控件可能需要一個STA線程運行並由一個ActiveX友好的容器正確託管,這不是您的測試控制檯應用程序所做的。從WinForms應用程序嘗試:

using System; 
using System.Windows.Forms; 
using AxSimpleActiveXControlLib; 

class Program 
{ 
    [STAThread] 
    static void Main() 
    { 
     var c = new AxSimpleActiveXControlLib.AxSimpleActiveXControl(); 

     var form = new Form 
     { 
      Controls = { c } 
     }; 

     form.Load += (s, e) => MessageBox.Show(c.GetSomeNumber().ToString()); 

     Application.Run(form); 
    } 
} 

這也可以幫助:

How to create a HelloWorld COM Interop in Visual Studio 2012

更新,當你添加一個引用到MFC ActiveX控件,您應該通過添加它Visual Studio WinForms工具箱,或使用AxImp.exe工具:

 
AxImp.exe SimpleActiveXControl.ocx 

這樣它將生成AxSimpleActiveXControlLib.dllSimpleActiveXControlLib.dll。前者將爲您的ActiveX控件包含System.Windows.Forms.Control衍生包裝。將兩者都添加到您的項目中,然後嘗試我上面發佈的代碼(根據您發佈的源代碼進行更新)。

+0

感謝您的回覆。 我使用VS 2010創建了Activex控件,方法是使用默認設置創建一個新的「MFC ActiveX控件」項目,然後使用類視圖向控件添加單個方法 - >右鍵單擊IDL文件 - >添加方法。你需要更多的細節嗎?我可以添加代碼,但是它是VS中創建項目的99%樣板。 – JohnnyW

+1

@JohnnyW,當你用我建議的WinForms測試它時會發生什麼?另外,究竟GetSomeString是什麼樣的? – Noseratio

+0

我把完整的代碼放在這裏:https://bitbucket.org/johnnyw3/simple-com-app/src – JohnnyW

相關問題