无法从C++调用.Net服务

本文关键字:Net 服务 调用 C++ | 更新日期: 2023-09-27 17:58:39

我已经编写了一个.NET Windows服务,其中内置了WCF服务。我可以从Visual Studio 2010中编写的C#客户端调用它。但是,我还需要从VisualStudio6中编写的MFC应用程序中调用它。我添加了COM Interop代码来尝试实现这一点,创建了一个snk文件,使用regasm注册并安装了它

WCF服务和MFC应用程序都是32位的。

我的WCF服务接口代码类似于以下

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IGASR" in both code and config file together.
[Guid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")]
[ServiceContract]
public interface IMyClass
{
    [OperationContract]
    void AddFile(string sFilename);
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)]
public class MyClass : IMyClass
{
    public void AddFile(string sFilename)
    {
        ...
    }
}

我的MFC代码看起来像:

CoInitialize(NULL);
MyNamespace::IMyClassPtr pDotNetCOMPtr;
HRESULT hRes = 
    pDotNetCOMPtr.CreateInstance(MyNamespace::CLSID_MyClass);
if (hRes == S_OK)
{
    pDotNetCOMPtr->AddFile ( _bstr_t(m_strFilename));
}
CoUninitialize ();   //DeInitialize all COM Components

但是,CreateInstance失败,HRESULT为-2147221164。即该类没有被注册。我错过了什么?

更新:我在接口的Guid行中添加了ComVisible(true),并在regasm调用中添加了/codebase选项。现在,从MFC应用程序中,CreateInstance成功了,但对AddFile的调用没有任何作用。没有错误,但没有调用该方法。我知道这一点是因为我已经登录了该方法。此方法在C#.NET客户端上运行良好。

所以,我越来越接近了,但现在不明白为什么方法调用没有创建错误,却没有调用我的.NET服务。

有人有什么想法吗?

无法从C++调用.Net服务

也许这会有所帮助。看起来比我想象的要复杂得多:)

为非托管C++客户端创建WCF服务

祝好运

您是否将C#项目设置为在其项目构建设置中注册COM互操作?或者,您需要运行regasm以手动向COM注册.NET DLL。