zoukankan      html  css  js  c++  java
  • C#如何静态调用C++中的方法(静态调用dll)

     当我们想要在C#中使用C++项目的方法时,这个时候就可以通过调用C++项目的dll来实现,它有静态和动态调用两种方法。

      DLL(Dynamic Link Library)文件为动态链接库文件,又称“应用程序拓展”,是软件文件类型。在Windows中,许多应用程序并不是一个完整的可执行文件,它们被分割成一些相对独立的动态链接库,即DLL文件,放置于系统中。当我们执行某一个程序时,相应的DLL文件就会被调用。一个应用程序可使用多个DLL文件,一个DLL文件也可能被不同的应用程序使用,这样的DLL文件被称为共享DLL文件。[1] (百度百科)

      我们在C++项目中写了如下的一个方法:

      

    那么只需将C++项目下Debug中的dll文件复制到我们C#的binDebug文件夹下即可。

    然后就是在代码中调用它。

    注意:

    添加属性:CallingConvention=CallingConvention.Cdecl

    主要是处理

     在使用托管代码调用非托管代码时,发生“对 PInvoke 函数“UseTwiHikVisionDllTest!UseTwiHikVisionDllTest.TwiHikVision::GetFirstPic”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。”

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace CSharp调用静态的dll
    {
    
        public partial class Form1 : Form
        {
            [DllImport("TestDll01.dll", CallingConvention = CallingConvention.Cdecl)]
            private extern static int testCount(int a, int b);
            public Form1()
            {
                InitializeComponent();
    
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                MessageBox.Show(testCount(12, 14).ToString());
            }
        }
    }

    运行结果:

  • 相关阅读:
    Leetcode 238. Product of Array Except Self
    Leetcode 103. Binary Tree Zigzag Level Order Traversal
    Leetcode 290. Word Pattern
    Leetcode 205. Isomorphic Strings
    Leetcode 107. Binary Tree Level Order Traversal II
    Leetcode 102. Binary Tree Level Order Traversal
    三目运算符
    简单判断案例— 分支结构的应用
    用switch判断月份的练习
    java基本打印练习《我行我素购物系统》
  • 原文地址:https://www.cnblogs.com/JsonZhangAA/p/5860573.html
Copyright © 2011-2022 走看看