C#调用C++编译Dll

C++编译DLL

这里以C++编译数组排序为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
extern "C" __declspec(dllexport) void array_sort(int* a, int len)
{
for (int i = 0; i < len; i++)
{
for (int j = i + 1; j < len; j++)
{
if (a[i] > a[j])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
}

注意库的编译方式x86/x64/Debug/Release

C#调用DLL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System.Runtime.InteropServices;
[DllImport("CppDll.dll", EntryPoint = "array_sort")]

static extern int array_sort(int[] a, int b);

private void button1_Click(object sender, EventArgs e)
{
int[] array = new int[5];
array[0] = 10;
array[1] = 12;
array[2] = 11;
array[3] = 15;
array[4] = 13;
array_sort(array,5);

for (int i = 0; i < 5; i++)
{
Console.Write(array[i].ToString()+",");
}
}

同样需要注意库的编译方式x86/x64/Debug/Release,C#中默认为Any CPU

参考:

[1].https://www.codeguru.com/csharp/csharp/cs_data/article.php/c4217/Calling-Unmanaged-Code-Part-1--simple-DLLImport.htm

坚持原创技术分享,您的支持将鼓励我继续创作!