简体   繁体   中英

how to expose a c# class as a com objects interface?

I have ac# class P2PLib.

 public int portRecv=10101;
    public int portSend = 10102;
    public int multicastPort=10103;
    int memberNum = 0;
    string data;
    string time;
    List<Member> MemberList = new List<Member>();
    public void DisplayMembers();
    public void start(...);
    public void join(..);
    public void leave(..);
    void add(...);
    void remove(...);

How do I create server side code of this class in my interop communication between c# and c++?

http://msdn.microsoft.com/en-us/library/aa645738(v=vs.71).aspx example shows how how we can write interfaces which can be groups of methods

but I am confused as to how will my variables like portsend and others will be initiated in c++ client side code.

---edit---can I keep persistent data with com interfaces? for eg the list mentioned above? Will I be able to create an object of this class in the unmanaged code communicating with the managed codes com object?

You cannot expose fields in a COM interface, only property and methods are supported. This is in general a good and widely adopted practice in C# programming, helps here as well:

public class PortWrapper {
   public int ReceivePort {
      get { return portRecv; }
      set { 
         if (value == portRecv) return;
         if (value < 256 || value > 65535) throw new ArgumentOutOfRangeException();
         portRecv = value;
         setupReceiver();
      }
   }
   // etc..

   private int portRecv=10101;
}

Fall into this pit of success by actually declaring an interface in your C# code. An all-around good idea since that lets you hide the implementation class details with [ClassInterface(ClassInterfaceType.None)] and expose the pure interface with [InterfaceType(ComInterfaceType.InterfaceIsDual)]. That's the natural COM way.

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