今日在tw的MSDN上忽然看到了关于c#调用c编写的dll,方法不错.又简单.以前还老写Active X,麻烦.具体例子,借用MSDN(v2005),如下
using System; using System.Runtime.InteropServices; class MainClass { [DllImport("User32.dll")] public static extern int MessageBox(int h, string m, string c, int type); static int Main() { string myString; Console.Write("Enter your message: "); myString = Console.ReadLine(); return MessageBox(0, myString, "My Message Box", 0); } }
说明
此示例创建一个外部 DLL,它将从示例 3 中的 C# 程序内调用。
代码
复制代码
// cmdll.c // compile with: /LD /MD int __declspec(dllexport) SampleMethod(int i) { return i*10; }
该示例使用两个文件 CM.cs
和 Cmdll.c
来说明 extern。C 文件是示例 2 中创建的外部 DLL,它从 C# 程序内调用。
代码
// cm.cs using System; using System.Runtime.InteropServices; public class MainClass { [DllImport("Cmdll.dll")] public static extern int SampleMethod(int x); static void Main() { Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5)); } } |
参考:
extern(C# 参考)
ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_csref/html/9c3f02c4-51b8-4d80-9cb2-f2b6e1ae15c7.htm
DllImportAttribute 类
ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.NETDEVFX.v20.chs/cpref11/html/T_System_Runtime_InteropServices_DllImportAttribute.htm
使用非托管 DLL 函数
ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_fxinterop/html/eca7606e-ebfb-4f47-b8d9-289903fdc045.htm