Inherit C++ interface

A

aleko

Hi,

I am trying to wrap some std C++ code so it can be used from C#. The
problem I'm having is that I can't seem to derive a ref class from a C+
+ interface. Compilation fails with C2811: "...can only inherit from a
ref class or interface class". AFAIK an abstract struct constitutes a
valid interface.
Here's an example:

// std C++
namespace blah
{
struct IThing
{
virtual ~IThing() {}
virtual void doIt() = 0;
};

class Thing : public IThing
{
public:
Thing() {}
virtual ~Thing() {}
void doIt() {}
};
} // namespace


// C++/CLI
namespace Blah
{
ref class Thing : public blah::IThing // C2811
{

};
}

Replacing the structs with __interfaces didn't help. Any ideas?

Thanks,

Aleko
 
D

David Lowndes

I am trying to wrap some std C++ code so it can be used from C#. The
problem I'm having is that I can't seem to derive a ref class from a C+
+ interface. Compilation fails with C2811: "...can only inherit from a
ref class or interface class". AFAIK an abstract struct constitutes a
valid interface.

The error message possibly only means one defined using the interface
name - see "interface class" in MSDN.

Dave
 
B

Ben Voigt [C++ MVP]

aleko said:
Hi,

I am trying to wrap some std C++ code so it can be used from C#. The
problem I'm having is that I can't seem to derive a ref class from a C+
+ interface. Compilation fails with C2811: "...can only inherit from a
ref class or interface class". AFAIK an abstract struct constitutes a
valid interface.

An interface it may be, but a native C++ interface. .NET classes can only
derive from .NET classes and .NET interfaces, hence the error message
referring to "ref class" and "interface class" (although "ref struct" and
"interface struct" would be allowed as well). C++/CLI code can work with
both native and managed data, but a managed class cannot derive from a
native anything. You'll have to *wrap* instead, meaning containment, which
is supported.

The basic problem is that .NET classes can be moved around by the garbage
collector. If that .NET class had a native base class, its "this" pointer
could change at any time. Native code isn't equipped to deal with this --
it doesn't emit the metadata the garbage collector needs to invisibly adjust
all the pointers and references to "track" the new memory address of the
object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top