C#调用c++的dll方法,动态调用c++dll的方法

文章目录


一、创建c++的dll

1.新建项目

右键解决方案>>添加>>新建项目

选择c++,windows,库,然后选择动态链接库

然后输入项目名称

2.删除vs自建的.cpp和.h文件

3.新建Algorithm.h和Algorithm.cpp


在Algorithm.h里面写上两个函数 add,munis

pragma关键字防止,h被重复引用

extern "C" __declspec(dllexport) 声明使用c的标准调用

c 复制代码
#pragma once
#include <stdio.h>
extern "C" __declspec(dllexport) const char* Getversion();
extern "C" __declspec(dllexport) int add(int a, int b);
extern "C" __declspec(dllexport) int minus(int a, int b);

在项目的源文件下面按照上面的方法新建一个Algorithm.cpp文件,新建的文件如图。

代码如下:

c 复制代码
#include "Algorithm.h"

const char* Getversion()
{
	return "v1.0.0";
}

int add(int a, int b)
{
	return a + b;
}

int minus(int a, int b)
{
	return a - b ;
}

4.编译c++

1.编译

1.此时右键编译的时候会报错,提示 "严重性 代码 说明 项目 文件 行 禁止显示状态

错误 C1010 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加"#include "pch.h""? Testdll C:\Users\admin\Desktop\TestSystem\Testdll\Algorithm.cpp 17

" 错误列表如图:

输出如图:

2.解决报错

右键项目》》属性》》C/C++》》预编译头,改成如图配置。点击应用

3.再次编译可以看到已经成功。

4.查看成功输出的dll。

二、创建c#项目

1.创建一个console控制台程序。

之后选择c#,windows,控制台。

创建好之后先点击生成c#程序,确认没有问题,进行下一步

2.把dll拷贝到c#生成的程序根目录。

3.在c#的program.cs类引入命名空间System.Runtime.InteropServices。

添加如下代码:

完整代码如下:

c 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program
    {
        [DllImport("Testdll.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static int add(int a, int b);
        [DllImport("Testdll.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static int minus(int a, int b);
        [DllImport("Testdll.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static IntPtr Getversion();
        
        static void Main(string[] args)
        {
            Console.WriteLine(add(1,5));
            Console.WriteLine(minus(1, 5));

            IntPtr pStr = Getversion();
            string version = Marshal.PtrToStringAnsi(pStr);
            Console.WriteLine(version);

            Console.ReadKey();
        }
    }
}

运行如图:

三、进阶,使用动态路径来调用c++的dll

这样做的好处是,dll不用放到exe的根目录,可以自己放到任何地方,方便管理。

1.新建一个DLLWrapper类。

代码如下:

c 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    public class DLLWrapper
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool FreeLibrary(IntPtr hModule);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool SetDllDirectory(string lpPathName);

        IntPtr pDll = IntPtr.Zero;
        public bool LoadDynamicLibrary(string path,string dlname)
        {
            if (File.Exists(Path.Combine(path, dlname)))
            {

                SetDllDirectory(path);
                pDll = LoadLibrary(dlname);

                if (pDll == IntPtr.Zero)
                {
                    Console.WriteLine("Failed to load DLL");
                    return false;
                }
                else
                {
                    Console.WriteLine("load DLL success");
                    return true;
                }
            }
            else
            {
                Console.WriteLine("DLL is not exist");
                return false;
            }
        }
        public bool FreeDllIntPtr()
        {
            bool resultFree = FreeLibrary(pDll);
            if (resultFree)
            {
                Console.WriteLine("DLL successfully unloaded.");
                return true;
            }
            else
            {
                Console.WriteLine("Failed to unload DLL.");
                return false;
            }
        }
    }
}

文件结构如图:

2.在program.cs调用这个类

区别如图:

代码如下:

c 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program
    {
        [DllImport("Testdll.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static int add(int a, int b);
        [DllImport("Testdll.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static int minus(int a, int b);
        [DllImport("Testdll.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static IntPtr Getversion();
        static void Main(string[] args)
        {
            DLLWrapper Wrapper = new DLLWrapper();
            //加载dll,传入dll的文件夹路径
            Wrapper.LoadDynamicLibrary(Environment.CurrentDirectory+ "\\Library", "Testdll.dll");

            Console.WriteLine(add(1,5));
            Console.WriteLine(minus(1, 5));

            IntPtr pStr = Getversion();
            string version = Marshal.PtrToStringAnsi(pStr);
            Console.WriteLine(version);

            //释放dll
            Wrapper.FreeDllIntPtr();
            Console.ReadKey();
        }
    }
}

运行如图:

源码链接如下:没有积分的可以留言给我,发送个人邮箱

项目下载链接

相关推荐
初圣魔门首席弟子7 分钟前
C++ STL string(字符串)学习笔记
c++·笔记·学习
自学AI的鲨鱼儿25 分钟前
ubuntu22.04安装gvm管理go
开发语言·后端·golang
AA陈超31 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P04-12 可缩放浮点数的曲线表
c++·游戏·ue5·游戏引擎·虚幻
旭意39 分钟前
C++微基础备战蓝桥杯之数组篇10.1
开发语言·c++·蓝桥杯
MediaTea1 小时前
Python:匿名函数 lambda
开发语言·python
R-G-B1 小时前
【06】C#入门到精通——C# 多个 .cs文件项目 同一项目下添加多个 .cs文件
开发语言·c#·c# 多个 .cs文件项目
青草地溪水旁2 小时前
VSCode C/C++ 构建任务配置文件 `tasks.json` 全字段深度解析
c语言·c++·vscode
数据知道2 小时前
Go基础:正则表达式 regexp 库详解
开发语言·mysql·golang·正则表达式·go语言
小蒜学长2 小时前
jsp基于JavaWeb的原色蛋糕商城的设计与实现(代码+数据库+LW)
java·开发语言·数据库·spring boot·后端
zhangfeng11332 小时前
亲测可用,R语言 ggplot2 箱线图线条控制参数详解,箱线图离散数值控制
开发语言·python·r语言·生物信息