C # example C ++ class library calls

 

First, create a solution and add a .netframework project in the solution, named FrameworkConsoleTest. Add a C ++ dynamic link library DLL project named EncryptBase.

 

Second, the C ++ project EncryptBase set with 64-bit generation deployments. (If your computer is a 32-bit system is located x86, 64-bit system is located x64)

 

 

Third, the solution to "current selection" starts.

 

Fourth, in EncryptBase header files, right - add - new item, add headers of a EncryptBase.h.

1, add the following code:

#ifndef _ENCRYPTBASE_H // define _ENRYPTBASE_H macro, in order to prevent duplicate references the header file 
#define _ENCRYPTBASE_H 

#ifdef __cplusplus // and this part is to tell the compiler, if you define __cplusplus (that is, if a cpp file, 
extern "C" {// cpp file because the macro defined by default), then using C language to be compiled 
#endif 


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

#ifdef the __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

 

Guess you like

Origin www.cnblogs.com/suterfo/p/12291129.html