3

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();
1
  • 1
    This cannot work, C# class != C++ class. You'll have to write a wrapper in the C++/CLI language or expose the C++ through COM. Commented Aug 20, 2011 at 9:48

2 Answers 2

3
  • 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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

@tenfour I believe, that writing COM object in C++ in order to just call a plain C++ class from .Net is too much overhead. The simplest solution is to create a simple dll with plain API, that can be called from .Net with dllimports

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.