81

I have a dll that was written in c++, I need to use this dll in my c# code. After searching I found that using P/Invoke would give me access to the function I need, but these functions are defined with in a class and use non-static private member variables. So I need to be able to create an instance of this class to properly use the functions. How can I gain access to this class so that I can create an instance? I have been unable to find a way to do this.

I guess I should note that the c++ dll is not my code.

Dan Vogel
  • 3,858
  • 7
  • 41
  • 57

6 Answers6

107

There is no way to directly use a C++ class in C# code. You can use PInvoke in an indirect fashion to access your type.

The basic pattern is that for every member function in class Foo, create an associated non-member function which calls into the member function.

class Foo {
public:
  int Bar();
};
extern "C" Foo* Foo_Create() { return new Foo(); }
extern "C" int Foo_Bar(Foo* pFoo) { return pFoo->Bar(); }
extern "C" void Foo_Delete(Foo* pFoo) { delete pFoo; }

Now it's a matter of PInvoking these methods into your C# code

[DllImport("Foo.dll")]
public static extern IntPtr Foo_Create();

[DllImport("Foo.dll")]
public static extern int Foo_Bar(IntPtr value);

[DllImport("Foo.dll")]
public static extern void Foo_Delete(IntPtr value);

The downside is you'll have an awkward IntPtr to pass around but it's a somewhat simple matter to create a C# wrapper class around this pointer to create a more usable model.

Even if you don't own this code, you can create another DLL which wraps the original DLL and provides a small PInvoke layer.

milleniumbug
  • 15,379
  • 3
  • 47
  • 71
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 2
    The statement of "There is no way to directly use a C++ class in C# code" is not correct. A static C++ function works the same way as C-style function and the instance functions can be declared as ThisCall calling convention by adding ThisObject pointing to the instance itself as the first argument. For details, you may want to read my [Blogs](http://www.xinterop.com/index.php/category/net/). You may also want to try our tool.(I am the author) – xInterop Apr 11 '14 at 01:09
  • 3
    Though a fine answer at the time, it's arguably better to use c++/CLI so as to avoid the manual creation of proxy functions - something that could become quite tedious rather quickly –  Feb 15 '15 at 17:40
  • 2
    Should the C++ proxy functions be surrounded by `extern "C" { .... }` or is it fine to do it purely in C++? – divB Apr 01 '15 at 06:26
  • 2
    @jaredpar where should I copy c++ dll? beside c# exe? I get System.EntryPointNotFoundException: 'Unable to find an entry point named '...' in DLL – Reza Akraminejad Jul 24 '19 at 10:01
38

Marshal C++ Class and use the PInvoke

C++ Code ,ClassName.h

class __declspec(dllexport) CClassName
{
 public:
    CClassName();
    ~CClassName();
    void function();

};

C++ Code, ClassName.cpp

CClassName::CClassName()
{
}

CClassName::~CClassName()
{
}

void CClassName::function()
{
    std::cout << "Bla bla bla" << std::endl;

}

C++ Code, ClassNameCaller.h file for the caller function

#include "ClassName.h"      

#ifdef __cplusplus
extern "C" {
#endif

extern __declspec(dllexport) CClassName* CreateClassName();

extern __declspec(dllexport) void DisposeClassName(CClassName* a_pObject);

extern __declspec(dllexport) void function(CClassName* a_pObject);


#ifdef __cplusplus
}
#endif

C++ Code, ClassNameCaller.cpp file for the caller function

#include "ClassNameCaller.h"


CClassName* CreateClassName()
{
    return new CClassName();
}

void DisposeClassName(CClassName* a_pObject)
{
    if(a_pObject!= NULL)
    {
        delete a_pObject;
        a_pObject= NULL;
    }
}

void function(CClassName* a_pObject)
{
    if(a_pObject!= NULL)
    {
        a_pObject->function();
    }
}

C# code

[DllImport("ClassNameDll.dll")]
static public extern IntPtr CreateClassName();

[DllImport("ClassNameDll.dll")]
static public extern void DisposeClassName(IntPtr pClassNameObject);

[DllImport("ClassNameDll.dll")]
static public extern void CallFunction(IntPtr pClassNameObject);

//use the functions
IntPtr pClassName = CreateClassName();

CallFunction(pClassName);

DisposeClassName(pClassName);

pClassName = IntPtr.Zero; 
Amir Touitou
  • 3,141
  • 1
  • 35
  • 31
  • 2
    Shouldn't there be a "dllexport" instead "dllimport" in the first file, ClassName.h? – P.W. Mar 07 '18 at 17:11
  • 1
    Yes , It is used to export this class to .Net project so we can use the CClassName class – Amir Touitou Mar 08 '18 at 05:20
  • 2
    This example really helped a lot, Thank you so much:-) – Ashish Rana Mar 28 '18 at 10:15
  • Hi. Not sure if this is too late, but can you show a modification of your code where I can pass strings through the function, modify them and then return them to the c# code? I've been trying but it won't allow me to add type names in a_pObject->function(std::string args1); – CausticLasagne Nov 04 '18 at 20:29
  • 1
    A side note, if you are getting a "BadImageFormatException", you might have to change the platform. I compiled my C++ code as x64 as usual, but the default project I created for the C# side was set to "Any CPU". This does not work, but it does once switched to x64. Make sure that matches. – clocktown Aug 29 '19 at 13:47
  • I needed to rename the C++ function named function to CallFunction to get this to work. – Ant Nov 04 '22 at 11:31
5

Here is a sample how to call C++ class method from VB - for C# you only have to rewrite the sample program in Step 4.

Dmitry Khalatov
  • 4,313
  • 3
  • 33
  • 39
4

The way I've done this is by creating a thin Managed C++ wrapper around my unmanaged C++ DLL. The managed wrapper contains "proxy" classes that wrap around the unmanaged code exposing the interface that's needed by the .NET application. This is a bit of double work but it allows quite seamless operation in normal environments. Things do get trickier with dependencies in some circumstances (such as ASP.NET) but you will probably not run into that.

Joris Timmermans
  • 10,814
  • 2
  • 49
  • 75
3

You may need to write an intermediary DLL (in C++, perhaps) that handles this for you and exposes the interface you need. Your DLL would be in charge of loading the 3rd party DLL, creating an instance of this C++ object, and exposing its member functions as needed via whatever API you design. You would then use P/Invoke to get at your API and cleanly manipulate the object.

Note: For the API of your DLL, try keeping the data types limited to primitives (long, int, char*, etc.) to prevent module boundary issues.

Brian
  • 3,457
  • 4
  • 31
  • 41
2

I agree with JaredPar. Creating instances of unmanaged classes in managed code should not be possible.

Another thing is - if you could recompile the DLL in managed C++ or make a COM component out of it, it would be much easier/

Paul Kapustin
  • 3,297
  • 5
  • 35
  • 45