zoukankan      html  css  js  c++  java
  • 利用C++创建DLL并C#调用

    日期:2018年11月26日

    环境:window 10,VS2015 community

    一、利用C++创建DLL

      1.新建项目;

      

      

      2.打开CreateDLL.cpp文件,并输入测试代码

      

     1 #include "stdafx.h"
     2 
     3 int __stdcall Add(int a, int b)
     4 {
     5     return a + b;
     6 }
     7 
     8 int __stdcall Sub(int a, int b)
     9 {
    10     return a - b;
    11 }
    DLL Test Code

      3.给工程添加一个.def文件,并在该文件中插入以下代码;

    1 LIBRARY CreateDLL
    2 EXPORTS
    3 Add @1,
    4 Sub @2,
    def Code

      注意这里的CreateDLL是工程名如果不同则应用程序连接库时会发生连接错误!

      其中LIBRARY语句说明该def文件是属于相应DLL的,EXPORTS语句下列出要导出的函数名称。我们可以在.def文件中的导出函数后加 @n,如Add@1,Sub@2,表示要导出的函数顺序号,在进行显式连时可以用到它。该DLL编译成功后,打开工程中的Debug目录,同样也会看到 CreateDLL.dll和CreateDLL.lib文件。

    二、使用C#调用DLL

      1.在新建的C#工程中插入以下代码;

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.Runtime.InteropServices;
     7 
     8 namespace AcmeCollections
     9 {
    10     class Program
    11     {
    12         [DllImport(@"C:UsersxxxxxDesktopstudyCreateDLLDebugCreateDLL.dll")]//DLL的位置
    13         public static extern int Add(int a, int b);
    14 
    15         [DllImport(@"C:UsersxxxxxDesktopstudyCreateDLLDebugCreateDLL.dll")]
    16         public static extern int Sub(int a, int b);
    17         static void Main(string[] args)
    18         {
    19             long ans;
    20             string str;
    21             
    22             ans = Add(9, 7);
    23             str = Convert.ToString(ans);
    24             Console.WriteLine(str);
    25             ans = Sub(9, 7);
    26             str = Convert.ToString(ans);
    27             Console.WriteLine(str);
    28             Console.ReadLine();
    29         }
    30     }
    C# Main Code

      2.运行结果;

      

    参考链接:http://www.cnblogs.com/daocaoren/archive/2012/05/30/2526495.html

  • 相关阅读:
    Django 的 CSRF 保护机制
    uni横向滑动
    uni模板
    下载excel文件,链接,通过按钮点击创建a标签实现
    vue去除input输入框空格适用于搜索查询框
    整理个人笔记Linux的一些常用命令
    简单概括一下JAVA中的ANT的配置
    谈谈JavaIO System对IO的三种支持
    JAVA使用类库对数组和各种Collection容器进行排序
    c语言自行设计矩形类构造函数
  • 原文地址:https://www.cnblogs.com/w54255787/p/10018804.html
Copyright © 2011-2022 走看看