1. 创建一个 C++ 动态链接库 (通过 VS 图形引导界面)
2. 添加 C++ 类
- CallC.cpp
- // CallC.cpp : 定义 DLL 应用程序的导出函数.
- //
- #include "stdafx.h"
- extern "C" __declspec(dllexport) int Add(int a , int b)
- {
- return a+b;
- }
- extern "C" __declspec(dllexport) int Sub(int a ,int b)
- {
- return a-b;
- }
3. 在相同解决方案下创建一个 C# 工程 (WinForm 就可以), 再添加一个调用 C++ 类库的函数转换类,
- CallCFunc.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Runtime.InteropServices;
- namespace WindowsFormsApplication1
- {
- class CallCFunc
- {
- [DllImport("CallC.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
- public static extern int Add(int a,int b);
- }
- }
注: 需要将 C++ 编译好的 Dll 拷贝到 C# 的 bin/Debug 下 (或 Release), 也可以一次性设置好 C++ 类库的 Dll 输出路径, 设置方式如下:
右键项目 -> 属性 -> 属性配置 -> 常规 -> 输出目录.
来源: http://www.bubuko.com/infodetail-2596494.html