简体   繁体   English

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

[英]Calling a C# dll from C++ using CoCreateInstance

My ProjectA a C# class library with one single class : 我的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;
        }
    }
}

I have checked Register for com interop using VS2010 which generated dll & tlb files for me, Ok until now. 我已经使用VS2010检查了Register for com interop ,它为我生成了dlltlb文件,好的,到目前为止。

My ProjectB a Win32 Dll application with single cpp file: 我的ProjectB是带有单个cpp文件的Win32 Dll应用程序:

    #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

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

Iam able to compile this Dll and everything looks ok until now. 我能够编译此Dll,并且到目前为止一切正常。

Question when I use my Win32 Dll & try calling the Add function this line : 当我使用Win32 Dll并尝试在此行中调用Add函数时出现问题:

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

Never gets passed, What might be the issue, Didnt it resgistered properly? 永远不会过去,这可能是问题所在,它没有正确地重新装好吗?

Kindly assist. 请协助。

The code as written doesn't give you a good way to diagnose the failure. 编写的代码无法为您提供诊断故障的好方法。 Write it like this instead: 改为这样写:

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

A common error code is 0x80040154, "Class not registered". 常见的错误代码是0x80040154,“类未注册”。 Etcetera. 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM