系列索引:C#入门系列教程索引
上一篇:C#入门教程08.02:托管dll调用
上一篇介绍了托管DLL调用,本部分介绍非托管,即非C#开发的DLL调用。
dll先创建一个用于测试的dll,dll就是一个简单加法。
使用qt创建一个简单的dll。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #if defined(_MSC_VER) || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) || defined(WIN32) \ || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) #define Q_DECL_EXPORT __declspec(dllexport) #define Q_DECL_IMPORT __declspec(dllimport) #else #define Q_DECL_EXPORT __attribute__((visibility("default" ))) #define Q_DECL_IMPORT __attribute__((visibility("default" ))) #endif #if defined(SUMDLL_LIBRARY) #define SUMDLL_EXPORT Q_DECL_EXPORT #else #define SUMDLL_EXPORT Q_DECL_IMPORT #endif extern "C" SUMDLL_EXPORT int sum (int a,int b) { return a+b; }
程序新建一个终端程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace sumprj { class Program { static void Main (string [] args ) { } } }
添加引用
1 2 [DllImport("sumdll.dll" , EntryPoint = "sum" , CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto) ]public extern static int sum (int a,int b ) ;
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ComponentModel;using System.Data;using System.Runtime.InteropServices;namespace sumprj { class Program { [DllImport("sumdll.dll" , EntryPoint = "sum" , CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto) ] public extern static int sum (int a,int b ) ; static void Main (string [] args ) { Int32 res = sum(1 , 3 ); Console.WriteLine(res); } } }
运行输出为
下一篇:C#入门教程08.04:代码混淆