C#调用C++类库例子

一、新建一个解决方案,并在解决方案下添加一个.netframework的项目,命名为FrameworkConsoleTest。再添加一个C++的动态链接库DLL项目,命名为EncryptBase。

二、将C++项目EncryptBase设为按64位生成部署。(如果你电脑是32位系统就设x86,是64位系统就设x64)

三、将解决方案设为“当前选定内容”启动。

四、在EncryptBase头文件,右键--添加--新建项,添加一个EncryptBase.h的头文件。

1、添加以下代码:

#ifndef _ENCRYPTBASE_H //定义_ENRYPTBASE_H宏,是为了防止头文件的重复引用
#define _ENCRYPTBASE_H

#ifdef __cplusplus //而这一部分就是告诉编译器,如果定义了__cplusplus(即如果是cpp文件, 
extern "C" { //因为cpp文件默认定义了该宏),则采用C语言方式进行编译
#endif


#ifdef DLL_EXPORTS  
#define DLL_EXPORTS __declspec(dllexport)   
#else  
#define DLL_EXPORTS __declspec(dllimport)   
#endif  
    
    DLL_EXPORTS int Sum(int value1, int value2);

#ifdef __cplusplus
}
#endif


#endif // !_ENCRYPTBASE_H

  

2、添加后如图所示:

五、在FrameworkConsoleTest项目的Program修改为以下代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace FrameworkConsoleTest
{
    class Program
    {
        [DllImport("EncryptBase.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern int Sum(int value1, int value2);

        static void Main(string[] args)
        {
            int sumValue = Sum(1, 2);
            Console.WriteLine("sumValue:"+sumValue);
        }
    }
}

修改后如图所示:

六、在EncryptBase项目,右键--属性--生成事件--生成后事件--命令行--编辑。设置生成后事件之后,编辑EncryptBase项目就不用每次将bin的dll复制到FrameworkConsoleTest项目了。

 

2、输入以下内容:

copy "$(OutputPath)$(TargetFileName)" "E:\Project\ArticleProject\AuthorizationTest\FrameworkConsoleTest\bin\Debug"
copy "$(OutputPath)EncryptBase.pdb" "E:\Project\ArticleProject\AuthorizationTest\FrameworkConsoleTest\bin\Debug"

3、设置后如下所示:

4、生成EncryptBase项目。

六、在FrameworkConsoleTest,右键属性--生成--取消勾选"首选32位"。

七、运行。

在FrameworkConsoleTest项目,组合按Ctrl+F5,可显示调用结果。如下图所示。

八、文件已上传,可点击下载。

https://files.cnblogs.com/files/suterfo/AuthorizationTest(Demo1).rar

猜你喜欢

转载自www.cnblogs.com/suterfo/p/12291129.html