C# calls two methods of C++ dll (managed and unmanaged)

C# calls C++ in two ways: (1) unmanaged calls; (2) managed calls.

First, use the unmanaged class to call the C++ dll.

1. First, create a new project in vs2010, select the win32 application, and set it as a DLL, as shown in the following figure

C# calls two methods of C++ dll (managed and unmanaged)

C# calls two methods of C++ dll (managed and unmanaged)

5. Create a new CPPDLL class on the dllConsoleApplication1 project and write the following code:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Runtime.InteropServices; //Must be added, otherwise DllImport will report an error

namespacedllConsoleApplication1

{

classCPPDLL

{

[DllImport("MyDLL.dll", CharSet = CharSet.Ansi)] //Introduce dll and set character set

//[DllImport("MyDLL.dll")] //Can replace the previous code

publicstaticexternintShow();

}

classProgram

{

staticvoidMain(string[] args)

{

CPPDLL.Show();

Console.ReadLine();

}

}

}

6. Running result:

C# calls two methods of C++ dll (managed and unmanaged)

2. Add the Functions.h header file and the Functions.cpp source file to the previous managed DLL project to use the OpenCV library to output and display images.

In Functions.h:

voidshow();

In Functions.cpp:

#include"Functions.h"

#include<opencv2/opencv.hpp>

usingnamespacecv;

voidshow()

{

Mat img = imread("E:\\Gallery\\abc.jpg");

imshow("src",img);

waitKey(0);

}

3. Use C++ managed classes for encapsulation. Added clrClass class. And click Project Managed DLL->Properties->Configuration Properties->Common Language Runtime Support->Common Language Runtime Support (, \clr) in "Solution", and then compile to generate DLL.

There is the following code in clrClass.h:

#pragmaonce

public ref class clrClass

{

public:

clrClass(void);

~clrClass(void);

intmember; //self add

voidshowImage(); //Self-added

};

There is the following code in clrClass.cpp:

#include"clrClass.h"

#include"Functions.h"//Self-added

clrClass::clrClass(void)

{

}

clrClass::~clrClass(void)

{

}

voidclrClass::showImage() //Self-added

{

show();

}

C# calls two methods of C++ dll (managed and unmanaged)

4. C# calls the Dll file generated by C++

Create a new C# console program, add reference -> browse -> select the generated DLL to add.

C# calls two methods of C++ dll (managed and unmanaged)

The above is the full text introduction of the two methods (managed and unmanaged) of C# calling C++ dll, I hope it will be helpful for you to learn and use program programming.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782352&siteId=291194637