C# ¹Ø¼ü×ÖexternÓ÷¨
ÐÞÊηûÓÃÓÚÉùÃ÷ÔÚÍⲿʵÏֵķ½·¨¡£extern ÐÞÊηûµÄ³£¼ûÓ÷¨ÊÇÔÚʹÓà Interop ·þÎñµ÷Èë·Ç
ÍйܴúÂëʱÓë DllImport ÊôÐÔÒ»ÆðʹÓã»ÔÚÕâÖÖÇé¿öÏ£¬¸Ã·½·¨»¹±ØÐëÉùÃ÷Ϊ static£¬ÈçÏÂÃæµÄʾÀýËùʾ£º[DllImport("avifil32.dll")]
private static extern void AVIFileInit();
×¢Òâ
extern ¹Ø¼ü×Ö»¹¿ÉÒÔ¶¨ÒåÍⲿ³ÌÐò¼¯±ðÃû£¬Ê¹µÃ¿ÉÒÔ´Óµ¥¸ö³ÌÐò¼¯ÖÐÒýÓÃͬһ×é¼þµÄ²»Í¬°æ±¾¡£
½« abstract£¨C# ²Î¿¼£©ºÍ extern ÐÞÊηûÒ»ÆðʹÓÃÀ´ÐÞ¸Äͬһ³ÉÔ±ÊÇ´íÎóµÄ¡£Ê¹Óà extern ÐÞÊηûÒâζ×Å·½·¨ÔÚ C# ´úÂëµÄÍⲿʵÏÖ£¬¶øÊ¹
Óà abstract ÐÞÊηûÒâζ×ÅÔÚÀàÖÐδÌṩ·½·¨ÊµÏÖ¡£×¢Òâ
extern ¹Ø¼ü×ÖÔÚʹÓÃÉϱÈÔÚ C++ ÖÐÓиü¶àµÄÏÞÖÆ¡£ÈôÒªÓë C++ ¹Ø¼ü×Ö½øÐбȽϣ¬Çë²Î¼û C++ Language Reference ÖÐµÄ Using extern to
Specify Linkage¡£
ÔÚ¸ÃʾÀýÖУ¬³ÌÐò½ÓÊÕÀ´×ÔÓû§µÄ×Ö·û´®²¢½«¸Ã×Ö·û´®ÏÔʾÔÚÏûÏ¢¿òÖС£³ÌÐòʹÓÃ´Ó User32.dll ¿âµ¼ÈëµÄ MessageBox ·½·¨¡£
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);
}
}
´ËʾÀýʹÓà C ³ÌÐò´´½¨Ò»¸ö DLL£¬ÔÚÏÂһʾÀýÖн«´Ó C# ³ÌÐòµ÷Óøà DLL¡£
// cmdll.c
// compile with: /LD
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));
}
}
Êä³ö
SampleMethod() returns
Ïà¹ØÎĵµ£º
1. ÃüÃû¹æ·¶
a) Àà
¡¾¹æÔò1-1¡¿Ê¹ÓÃPascal¹æÔòÃüÃûÀàÃû£¬¼´Ê××ÖĸҪ´óд¡£
¡¾¹æÔò1-2¡¿Ê¹ÓÃÄܹ»·´Ó³À๦ÄܵÄÃû´Ê»òÃû´Ê¶ÌÓïÃüÃûÀà¡£
¡¾¹æÔò1-3¡¿²»ÒªÊ¹ÓÓI”¡¢“C”¡¢“_”µÈÌØ¶¨º¬Òåǰ׺¡£
¡¾¹æÔò1-4¡¿×Ô¶¨ÒåÒì³£ÀàÓ¦ÒÔException½áβ¡£
¡¾¹æÔò1-5¡¿ÎļþÃûÒªÄÜ·´Ó ......
ʹÓà PlaySound ÔÚÒÆ¶¯É豸Éϲ¥·ÅÉùÒôÎļþ¡£´Ë´úÂëʹÓà System.Runtime.InteropServices
µ÷Óà Compact Framework µÄ CoreDll.DLL µÄ PlaySound ·½·¨
¹ØÓÚ²¥·ÅʵÏÖ£º
//²¥·Å±êÖ¾
private enum Flags
{
&n ......
//TransmitFileʵÏÖÏÂÔØ
protected void Button1_Click(object sender, EventArgs e)
{
/*
΢ÈíΪResponse¶ÔÏóÌṩÁËÒ»¸öÐµķ½·¨TransmitFileÀ´½â¾öʹÓÃRespo ......
תÒåÐòÁÐ ×Ö·ûÃû³Æ Unicode ±àÂë
\' µ¥ÒýºÅ 0x0027
\" Ë«Òýº ......
ÀûÓÃWM_COPYDATAÔÚÓ¦ÓóÌÐò¼ä´«µÝÊý¾ÝºÜ¼òµ¥,¿ªÏúҲС
Ò»¡¢´«µÝÊý¾Ý²¿·Ö
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ThreeTorches
{
public struct Copydatastru ......