2007年8月29日星期三

.Net 中使用非托管DLL

(由于EXPRES版不可以创建DLL,只能拿CB来创建DLL做测试了)

1,使用CB编写一个DLL
extern "C" void __declspec(dllexport) __stdcall HelloWorld(const char *pStr,
double &pReData,
char pReStr[100]
)
{
MessageBox(0, Format("Hello:%s",ARRAYOFCONST((pStr))).c_str(), "Info", MB_OK + MB_ICONINFORMATION);
pReData = 1234567;
strcpy(pReStr,"Hello From Dll");
}

2,把编译好的DLL放到工程的BIN目录下的Release或Debug目录下
3,在类中声明(using System.Runtime.InteropServices;)
[DllImport("TestDll.dll")]
public static extern void HelloWorld(string pStr,ref double pRdata,StringBuilder pRstr);
4,使用
double tData = 11;
StringBuilder tStr = new StringBuilder();
HelloWorld("Your Name", ref tData, tStr);
MessageBox.Show(String.Format("Double:{0} String:{1}",tData,tStr.ToString()));

附:
1,如果是引用类型(或指针),使用ref来声明变量
2,需要从参数中传出char*类型是,那就要用StringBuilder
3,回调使用delegate

public delegate bool CallBack(int hwnd, int lParam);
public class EnumReportApp {
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);

public static void Main()
{
CallBack myCallBack = new CallBack(EnumReportApp.Report);
EnumWindows(myCallBack, 0);
}

public static bool Report(int hwnd, int lParam) {
Console.Write("窗口句柄为");
Console.WriteLine(hwnd);
return true;
}
}
BTW:
因为一直过着深居简出的生活,上周并没有到徐家汇去买书(懒啊),就在附近转转看看,
看到有家新华书店,进去瞅了瞅,真是令人寒心,偌大的一个书店,连一本开发方面的书都没有。
算了,去展会时顺带看看,买本回来。

没有评论: