Click here to Skip to main content
15,888,202 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
I want to callback C# method from "C++ COM dll", Here is the strategy I took.

Step 1:In C++ Server.dll in idl I declared 2 class Class1 and Class2 as below.

C++
[
       object,
       uuid(54120D45-09DE-4e61-AA30-858CE4C472B5),
       oleautomation,
       helpstring("Class1 Interface"),
       pointer_default(unique)
    ]
    interface IClass1 : IUnknown
    {
      [helpstring("GetCls2Ptr")] HRESULT GetClass2InterfacePtr(IClass2 * ptrCls);
      [helpstring("SayHellow")] HRESULT SayHellow();
    }
    interface IClass2 : IUnknown
    {
      [helpstring("CallMe")] HRESULT CallMe();
    }
    
    In Class1.h
    class Class1 :public IClass1 
    {
      IClass2 **class2Obj;
     STDMETHOD GetClass2InterfacePtr(IClass2 * ptrCls)
      {
        class2Obj= (&ptrCls);
        return S_OK;
      }
    STDMETHOD SayHellow(void)
      {
       (*class2Obj)->CallMe();
       return S_OK;
      }
    }


Step 2:
PERL
TlbImp c:\Server.tlb to generate Managed dll [ServerManaged.dll].


Step 3:
PERL
refer ServerManaged.dll in C# 


Step 4:
PERL
In C# I declared 1 class as below



C#
using ServerManaged;
namespace Test1
{
public class CSClass : IClass2
{
  IClass1 IClass1Obj=null;
  public CSClass()
  {
   //initialising IClass1Obj
   //some code
   //Set Interface objet back to C++
   IClass1.GetClass2InterfacePtr(this);
   //call SayHellow, which inturn will call CallMe() on this
   IClass1.SayHellow();

  }
  void CallMe()
  {
    MessageBox.Show("Hurray I got a call!!");
  }
}



Step 5:
I code is compiling fine, running fine, executing fine, No exception reported


PERL
But the problem is I can't say "Hurray I got a call!!" :( 


Thanks in advance
Posted
Updated 5-Nov-15 20:23pm
v3

1 solution

If you only what to set a callback function it is fairly easy, as described in my article.

A more complex scenario with classes is in the article How to Marshal a C++ Class displayed.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900