Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C++ class instance in C#

Tags:

c++

c#

.net

interop

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();

2 Answers

  • 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

like image 59
Ajay Avatar answered Mar 17 '26 11:03

Ajay


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.

like image 26
Vladimir Perevalov Avatar answered Mar 17 '26 10:03

Vladimir Perevalov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!