Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c++ cli - Implementing an interface declared in C# from C++/CLI

Say I have a C# interface called IMyInterface defined as follows:

// C# code
public interface IMyInterface
{
  void Foo(string value);
  string MyProperty { get; }
}

Assume I also have a C++/CLI class, MyConcreteClass, that implements this interface and whose header is declared as follows:

// C++/CLI header file
ref class MyConcreteClass : IMyInterface
{
public:

};

How does one implement the method Foo and the property MyProperty in the C++/CLI header?

My attempt results in the following compile error:

error C3766: 'MyConcreteClass' must provide an implementation for the interface method 'void IMyInterface::Foo(System::String^ value)'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
public ref class MyConcreteClass : public IMyInterface
{
 public:
  virtual void __clrcall Foo(String^ value) sealed;  

  virtual property String^ __clrcall MyProperty 
         { String^ get() sealed { String::Empty; } }
};

Interfaces need to be defined as virtual. Also note the "public IMy.." after the class decleration, it's a slighly different syntax than C#.

If you can, seal the interface members to improve performance, the compiler will be able to bind these methods more tightly than a typical virtual members.

Hope that helps ;)

I did not compile it but looks good to me... Oh and also, defining your methods as __clrcall eliminates dangers of double thunk performance penalties.

edit the correct syntax for a property is:

public ref class MyConcreteClass : public IMyInterface
{
 public:
  virtual property String^ MyProperty 
  {
    String^ get() sealed { return String::Empty; };
    void set( String^ s ) sealed { };
  }
};

or, when putting the definition in the source file:

public ref class MyConcreteClass : public IMyInterface
{
 public:
  virtual property String^ MyProperty 
  {
    String^ get() sealed;
    void set( String^ s ) sealed;
  }
};

String^ MyConcreteClass::MyProperty::get()
{
  return String::Empty;
}

void MyConcreteClass::MyProperty::set( String^ )
{
  //...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...