您的位置:首页 > 编程语言 > C语言/C++

Visual Studio 2019 使用C语言创建动态链接库(Dll)并使用C语言和C#实现调用

2019-08-15 11:58 931 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_34976988/article/details/99625533

一、创建DLL

1、建立动态链接库项目

 

2、创建头文件和源文件

    删除 framework.h、dllmain.c 等现有文件(照顾VS2013等低版本),创建新的头文件 Mydll.c Mydll.h

   Mydll.h头文件代码如下:

#include<stdio.h>

_declspec(dllexport) void test_print(char const* str);
_declspec(dllexport) int test_sum(int a, int b);

Mydll.c 代码如下:

#include<stdio.h>
#include"Mydll.h"
void test_print(char const* str)
{
    printf("测试输出的内容是:%s\n", str);
}

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

 

3、配置C环境

     右键项目 --> 属性 --> C/C++ --> 预编译头 -->预编译头  改为创建;如果第二步删除了pch.h,在预编译头文件里也要删除pch.h

     右键项目 --> 属性 --> C/C++ --> 高级 -->编译为 改成 编译为 C 代码 (/TC)

     应用后保存即可

4、生成dll

    右键生成即可得到dll文件

 

二、C语言动态调用dll

C语言和C#都可以通过多种方法调用dll,动态调用是在运行时完成的,也就是程序需要用的时候才会调用,动态调用不会在可执行文件中写入DLL相关的信息。

动态调用主要用到LoadLibrary,GetProcAddress和FreeLibrary三个函数

一、创建C控制台运用,代码如下:

#include <stdlib.h>
#include <windows.h>
#include<stdio.h>

int main(int argc, char const* argv[])
{
    void(* test_print)(char const*) = NULL;
    int(* test_sum)(int, int) = NULL;

    HMODULE module = LoadLibraryA("CreatDll.dll");
    if (module == NULL) 
    {
        system("error load");
    }

    test_print = (void(*)(char const*))GetProcAddress(module, "test_print");
    test_sum= (int(*)(int, int))GetProcAddress(module, "test_sum");
    
    if ( test_print != NULL) 
    {
         test_print("输出测试");
    }
    else {
        system("function p_test_print can not excute");
    }
    int sum_result;
    if ( test_sum != NULL) 
    {
        sum_result =  test_sum(234, 432);
        printf("求和结果是:%d\n", sum_result);
    }
    else {
        system("function p_test_print can not excute");
    }
    FreeLibrary(module);
    system("pause");
    return 0;
}

2、将刚刚生成的DLL文件拷贝到控制台项目根目录即可。

3、运行结果

 

三、C#调用dll

C#通过映射同意可以动态调用dll,这里简单介绍静态调用dll。

1、创建C#控制台应用,添加如下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace TestDll
{
    class Program
    {
        [DllImport("CreatDll.dll", EntryPoint = "test_sum", CallingConvention = CallingConvention.Cdecl)]
        public static extern int test_sum(int a,int b);
        
        static void Main(string[] args)
        {
            int a = 234, b = 432;
            int sum = 0;
            Console.WriteLine("{0}+{1}={2}",a,b,test_sum(a,b));
            Console.ReadKey();
        }
    }
}
2、将生成的DLL文件拷贝到C#项目目录的Debug下,即可调用,调用结果如下:

 

 

项目源代码点击这里下载

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: