Visual Studio 2019 使用C語言創建動態鏈接庫(Dll)並使用C語言和C#實現調用


一、創建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下,即可調用,調用結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM