C# 调用C++dll

1.  C++  win32项目   dll 空项目

    添加CPPDemo.cpp 

     

<span style="white-space:pre">		</span>extern "C" __declspec(dllexport) int Add(int x, int y) 
<span style="white-space:pre">		</span> { 
<span style="white-space:pre">			</span>   return x + y; 
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span> extern "C" __declspec(dllexport) int Sub(int x, int y) 
<span style="white-space:pre">		</span>{ 
<span style="white-space:pre">			</span>   return x - y; 
<span style="white-space:pre">		</span> }
<span style="white-space:pre">		</span> extern "C" __declspec(dllexport) int Multiply(int x, int y) 
<span style="white-space:pre">		</span> { 
<span style="white-space:pre">			</span>   return x * y; 
<span style="white-space:pre">		</span> }
<span style="white-space:pre">		</span> extern "C" __declspec(dllexport) int Divide(int x, int y) 
<span style="white-space:pre">		</span> { 
<span style="white-space:pre">			</span>   return x / y; 
<span style="white-space:pre">		</span> }
    生成.dll和.lib
2. C#   控制台应用程序    将.dll放在debug目录下
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">  添加类</span><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">CPPDLL.cs</span>
     <pre name="code" class="csharp">        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Runtime.InteropServices; //添加
 
        namespace ConsoleApplication1
        {
            class CPPDLL
            {
                [DllImport("cdll.dll", CallingConvention = CallingConvention.Cdecl)]    //Cdecl很重要
                public static extern int Add(int x, int y);

                [DllImport("cdll.dll",CallingConvention = CallingConvention.Cdecl)]  
                public static extern int Sub(int x, int y);

               [DllImport("cdll.dll",CallingConvention = CallingConvention.Cdecl)] 
               public static extern int Multiply(int x, int y);

               [DllImport("cdll.dll",CallingConvention = CallingConvention.Cdecl)] 
                public static extern int Divide(int x, int y);
            }
        }

修改program.cs

       static void Main(string[] args)
        {
            int result = CPPDLL.Add(10, 20);   
            Console.WriteLine("10 + 20 = {0}", result); 


            result = CPPDLL.Sub(30, 12);   
            Console.WriteLine("30 - 12 = {0}", result);  


            result = CPPDLL.Multiply(5, 4);  
            Console.WriteLine("5 * 4 = {0}", result); 


            result = CPPDLL.Divide(30, 5);  
            Console.WriteLine("30 / 5 = {0}", result);
        }
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值