previously wrote a C + + code, want to write to him in C # interface, that is to let this code in C # can run. Look at Baidu's many methods, are said to be encapsulated into a DLL call, but follow the steps to always appear a variety of errors, such as the following:
And the delay can not be solved, today unexpectedly someone told me directly to the DLL extracted to the C # project bin file can be, three views are ruined .... Tried a bit, really successful, here to put the concrete steps and everyone to say, to avoid
Waste a lot of time on this issue.
First, let's build a C + + project (in order to get the DLL) and wrap the function you intend to use in C # with the following format extern "C" __declspec (dllexport):
#include <stdio.h> #include <iostream> #include <string.h> #include <string>using namespace std ; void output () {cout << "Hello World" << Endl;} extern "C" __declspec (dllexport) int sum (int a, int b) {output (); return a + b;}
Then right-click on the project name--Properties--Configure Properties--General---> change configuration type to DLL
Then compile, will be the same as the project name of the Debug folder under the DLL extraction, placed in C # project bin file-->debug, run can.
Add the code between the package and the Begin,end, and then call the function directly in the main program.
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using system.runtime.interopservices;//to add namespace csharp{ class program { // begin [ DllImport ("Tach.dll", entrypoint = "sum", CharSet = CharSet.Ansi, callingconvention = Callingconvention.stdcall)] public static extern int sum (int a,int b); End static void Main (string[] args) { int res = SUM (1, 2); Console.WriteLine (res);}}}
result, run successfully!
Because there is not a lot of testing, this method may have problems (feeling and online are not the same ...). If this method has errors or everyone has a better way, please leave a message under the blog, hope can help everyone!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Teaches you to quickly call C + + code (functions) in C #