How to call C/C++ sytle function from C# solution?

1. Write native(unmanaged) code with C/C++, and make sure compile it as a DLL, the sample is as below

#include <iostream>
using namespace std;

extern "C"
{
  _declspec(dllexport) int AddTwoNumber(int x, int y);
}
int AddTwoNumber(int x, int y)
{
  return x+y;
}

2. Write managed code with C#, we can put it in a console application, like below:

static void Main(string[] args)
{
  int result = AddTwoNumber(2, 77);
  Console.WriteLine(result);
  Console.Read();
}

[DllImport("E:\TestTools\UnManagedSolution\Debug\UnManagedSolution.dll", CallingConvention = CallingConvention.Cdecl)] // full path to reference the dll file
//[DllImport("E:\TestTools\UnManagedSolution\Debug\UnManagedSolution.dll", CallingConvention=CallingConvention.StdCall)] // just different CallingConvention
//[DllImport("UnManagedSolution.dll"), CallingConvention] // make sure copy the dll to the same folder with exe file
public extern static int AddTwoNumber(int x, int y);

Now it just works, try it! ^_^

原文地址:https://www.cnblogs.com/researcher/p/4990096.html