简体   繁体   中英

Calling a C# dll from C++ using CoCreateInstance

My ProjectA a C# class library with one single class :

  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.

My ProjectB a Win32 Dll application with single cpp file:

    #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.

Question when I use my Win32 Dll & try calling the Add function this line :

 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". Etcetera.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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