user595010
user595010

Reputation:

How to use C++ class instance in C#

I have a DLL that contains a class that inherits from another abstract C++ class defined as following:

class PersonInterface
{
public:
    virtual int __stdcall GetName() = 0;
};

The DLL exports a function that can be used in C# as following (following method is part of static class PersonManager):

[DllImport( "person.dll", CallingConvention = CallingConvention.Cdecl )]
public static extern bool GetPerson( out PersonInterface person  );

where PersonInterface is defined in C# class as following:

[StructLayout( LayoutKind.Sequential )]
public class PersonInterface
{
}

I can successfully retrieve the C++ class instance like this:

PersonInterface person;
bool retrieved = PersonManager.GetPerson( out person );

However, the retrieved object is not of any use until GetName method can be called.

What else needs to be done in order to be able to be able to invoke GetName method on retrieved person object?

string name = person.GetName();

Upvotes: 3

Views: 3296

Answers (2)

Ajay
Ajay

Reputation: 18411

  • Compile your C++ DLL using /clr compiler option.
  • Write up a managed class using public ref class syntax, and have pointer to your native class in this class. Expose all methods from this managed class and forward all calls to your native class.
  • Import this DLL as assembly in your c# project and use this class as you would use any other .NET class.

You need to compile only few source files using /clr flag, not all. Let all native source files be compiled as native. Your DLL will be linked to VC runtime DLL as well as .NET runtime DLL.

There is lot to managed class, /clr, Interoperability/Marshalling, but at least get started.

You may choose your favorite articles from here

Upvotes: 3

Vladimir Perevalov
Vladimir Perevalov

Reputation: 4159

You`ll have to write a wrapper in C++ (it may be managed C++), where you call you C++ clasess and expose either flat dll functions, which can be called from .Net, or .Net classes (if you used managed C++), that will be accessible from .Net.

Upvotes: 1

Related Questions