使用CoCreateInstance从C ++调用C#dll

时间:2013-06-26 10:31:42

标签: c# c++ com comvisible

我的 ProjectA 一个C#类库,只有一个类:

  namespace myLib
  {
    // Interface declaration.
    [Guid("Some GUID")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface ICsClass
    {
        [DispId(1)]
        int Add(int Number1, int Number2);
    };

    [Guid("Some GUID")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("myLib.CsClas")]       
    public class CsClas : ICsClass
    {
         public int Add(int a, int b)
        {
            return a + b;
        }
    }
}

我使用生成Register for com interop&的VS2010 dll检查了tlb Win32 Dll文件给我,好,直到现在。

我的 ProjectB 具有单个cpp文件的 #import "MyLib.tlb" raw_interfaces_only using namespace MyLib; 个应用程序:

#ifdef __cplusplus
extern "C"{
#endif
    __declspec(dllexport) long Add(int a,int b)
    {
        CoInitialize(NULL); 
        long lResult = 0;       
        // Use Smart pointer
        CComQIPtr <ICsClass> spCoClass;
        if (SUCCEEDED (spCoClass.CoCreateInstance(L"myLib.CsClas")))
        {
            spCoClass->Add(a,b,&lResult);   
            wprintf(L"The result is %d\n", lResult);
            std::cout << "#"+lResult << '\n'; 
        }
        CoUninitialize();
        return lResult;
    }
#ifdef __cplusplus
}
#endif

...............

 SUCCEEDED (spCoClass.CoCreateInstance(L"myLib.CsClas"))

.......

我能够编译这个Dll,直到现在一切看起来还不错。

当我使用Win32 Dll&amp;尝试调用添加功能 这一行:

{{1}}

永远不会过去,可能是什么问题,它没有正确地重新注册吗?

请帮忙。

1 个答案:

答案 0 :(得分:2)

编写的代码不能为您提供诊断故障的好方法。这样写它:

    HRESULT hr = spCoClass.CoCreateInstance(L"myLib.CsClas");
    if (SUCCEEDED(hr)) {
       // etc..
    }

常见错误代码为0x80040154,“未注册类”。等等。

相关问题