C++封装成dll文件及C#调用流程

mac2024-03-25  29

一、C++程序封装成dll文件

1、新建动态链接库项目

生成的文件包含以下文件:

其中,targetver.h可以声明要导出的dll中函数名;Dll1.cpp实现要导出的函数功能。

targetver.h内容如下:

#pragma once // 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。 // 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并 // 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。 #include <SDKDDKVer.h> extern "C" _declspec(dllexport) int _stdcall Add(int a,int b);

Dll1.cpp内容如下:

// Dll1.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" int _stdcall Add(int a,int b) { return a + b; }

注意:

1、此时编译使用Debug X64

2、_declspec(dllexport)是用于Windows中的动态库中,声明导出函数、类、对象等供外面调用,即将函数、类等声明为导出函数,供其它程序调用,作为动态库的对外接口函数、类等。

__stdcall:Windows API默认的函数调用协议。

2、配置属性

3、编译生成dll

 参考网址:https://blog.csdn.net/qq_42855293/article/details/83579115

二、C#程序调用

1、新建C#控制台应用程序

namespace ConsoleApp1 { class Program { static void Main(string[] args) { int a = 2; int b = 3; int c =0; c=Class1.Add(a,b); } } class Class1 { //bool __stdcall SetLaserMode(int laserType,int standby,float frequency, float pulseWidth); //[DllImport("Dll1.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)] [DllImport("Dll1.dll")] public static extern int Add(int a, int b); } }

2、添加Dll1.dll文件到C#工程下

注意:C#的编译器选择Debug X64

3、总结注意

一定要注意生成dll 使用debug x64,在C#程序调用时也要使用 debug x64编译器,否则程序会报错。

最新回复(0)