zoukankan      html  css  js  c++  java
  • C#调用C++生成的动态链接库DLL

    一、背景

    由于要使用C#写app,所以要把C++生成的DLL在C#中调用,所以就涉及怎样去调用外部的dll问题。

    二、C#调用外部DLL

    首先先看下C#调用外部DLL的代码

    using System.Runtime.InteropServices;
    
    namespace WzCan_DeviceExploer
    {
        public partial class Form2 : Form
        {
           
            [DllImport("testmaster.dll", EntryPoint = "WzCanOpenInit", CallingConvention = CallingConvention.StdCall)]  //CallingConvention指示入口点的调用约定
             public static extern int WzCanOpenInit(int DevIndex);  //声明DLL中的函数WzCanOpenInit,要注意要在函数前加上 public static extern                  
            public Form2()
            {
                InitializeComponent();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                int res;
                res = WzCanOpenInit(0);   //外部dll在C#中的调用                  
                this.Close();             //关闭当前CAN SETTING窗口
            }
            private void button2_Click(object sender, EventArgs e)
            {
                this.Close();            //退出当前CAN SETTING窗口
            }
        }
    }
    

    如上程序所示,
    1)调用dll需要引用命名空间 using System.Runtime.InteropServices
    2)testmaster.dll为外部的dll,程序启动时还需将其放在Dubug文件夹中,否则启动不了。
    3) CallingConvention是指示入口点的调用约定,默认情况下,C和C++使用的Cdecl调用,但由于DLL在C++的函数TESTMASTER_API DWORD __stdcall WzCanOpenInit(DWORD DevIndex),包含有__stdcall的关键字,所以 CallingConvention要设置成CallingConvention.StdCall
    4)声明外部函数则使用public static extern

    三、参考文档

    http://www.cnblogs.com/kevin-top/archive/2010/06/04/1751425.html //C#调用外部DLL
    http://www.xuebuyuan.com/645807.html //C# 导入dll时CallingConvention的设置问题

    by 羊羊得亿
    2017-06-16 ShenZhen

  • 相关阅读:
    文件路径与操作系统
    试验10
    shiyan9
    sql
    shiyan8
    iostream
    shiyan7
    CDMA
    试验6
    试验5
  • 原文地址:https://www.cnblogs.com/yangxuli/p/7026275.html
Copyright © 2011-2022 走看看