gpt4 book ai didi

c# - 无法运行非常简单的 COM 客户端

转载 作者:行者123 更新时间:2023-11-30 20:48:21 24 4
gpt4 key购买 nike

当我尝试为我用 C++ 编写的非常简单的 COM 服务器运行一个非常简单的 COM 客户端时,我遇到了各种错误。 COM 服务器是用 C++ 编写的,只有一个方法“GetSomeString”。我构建了 COM 服务器的 ocx,使用 regsrv32 注册它,并从以下 C# 控制台应用程序引用它:

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 .任何帮助将不胜感激。

最佳答案

这当然取决于 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。前者将包含 System.Windows.Forms.Control 派生的 ActiveX 控件包装器。将两者都添加到您的项目中,然后尝试我在上面发布的代码(根据您发布的源代码进行了更新)。

关于c# - 无法运行非常简单的 COM 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24723272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com