C#调用C++动态链接库DLL

参考https://www.cnblogs.com/sntetwt/p/11448435.html
1.打开vs2022,创建新项目
image

2.选择C++控制台空项目
image

3.添加C++文件 Test.cpp,内部代码如下

#include <iostream>
#include <Windows.h>
using namespace std;
int Add(int a, int b)
{
    return a + b;
}

void Show()
{
	MessageBoxA(NULL, "Hello from DLL!", "DLL Message", MB_OK);
}

4、添加模块定义文件
源文件 -> 添加 -> 新建项 -> 模块定义文件(.def)
添加代码如下
LIBRARY
LIBRARY DLLTest.dll
EXPORTS
Add
Show
项目结构如下
image

5.修改配置属性
选中项目右键属性,配置属性,常规,配置类型,选择动态库(.dll)。平台选择win32
image

6.更改平台为win32
image
image

7.生成项目,拿到生成的dll,放在C#项目的Debug或Release目录下,调用
image
代码如下

[DllImport("D:\\DLLTest\\Debug\\DLLTest.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
[DllImport("DLLTest.dll", EntryPoint = "Show", CallingConvention = CallingConvention.Cdecl)]
public static extern void ShowMsg();
private void ButtonVCDLL_Click(object sender, RoutedEventArgs e)
{
    int ret2 = Add(1, 2);
    ShowMsg();
}

image
image

posted @ 2025-08-22 10:34  山水蒙!  阅读(109)  评论(0)    收藏  举报