前一篇文章分析了制作口语考试系统的几种方法,JMF好像口碑不是很好,而且客户端还需要下载JMF的框架,RED5和FMS都没有使用过,而微软好像没有提供类似java的applet那样的网页端小程序,因为胖客户端应用已经被flash占了比较大的又是,silverlight也是刚刚开始推广。所以,我决定选择使用C/S的架构。
第一个要解决的问题就是就是在托管程序中调用非托馆函数的问题。
使用DllImport来调用win32 API. DllImport在命名空间System.Runtime.InteropServices中.
DllImport是用于指明声明的函数。
DllImport的使用形式为:[DllImport("User32.dll", EntryPoint = "MessageBox", CharSet = CharSet.Auto)]
其中,User32.dll是要调用的dll名,EntryPoint指明了调用的入口点,即是调用dll中的哪个函数。CharSet指明了调用的字符集。字符集包括ansi和unicode两种。
DllImport描述的函数必须是用static和extern加以修饰。
举例说明:
声明原型:
1
using System;2
using System.Collections.Generic;3
using System.Text;4
using System.Runtime.InteropServices;5

6
namespace RecordTest7


{8
class LipWrap9

{10
[DllImport("User32.dll", EntryPoint = "MessageBox", CharSet = CharSet.Auto)]11
public static extern int MsgBox(int hWnd, String text, String caption, uint type);12
}13
}14
调用函数
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.Runtime.InteropServices;
9
10 namespace RecordTest
11 {
12 public partial class Form1 : Form
13 {
14 public Form1()
15 {
16 InitializeComponent();
17 }
18
19 private void button1_Click(object sender, EventArgs e)
20 {
21 LipWrap.MsgBox(0, "hello,world", "njj", 0);
22 }
23
24
25
26 }
27
28
29
30
31 }
运行程序后,当点击窗口中的按钮时,就会出现一个hello world的弹出窗口。
附:由于托管代码和非托管代码的数据类型是不兼容的,必须使用托管代码中的数据类型对非托管代码的数据类型进行替换
下表引自MSDN,列出了非托管代码对应的托管代码的数据类型
下表列出了在 Win32 API(在 Wtypes.h 中列出)和 C 样式函数中使用的数据类型。许多非托管库包含将这些数据类型作为参数传递并返回值的函数。第三列列出了在托管代码中使用的相应的 .NET Framework 内置值类型或类。某些情况下,您可以用大小相同的类型替换此表中列出的类型。
| Wtypes.h 中的非托管类型 | 非托管 C 语言类型 | 托管类名 | 说明 |
|---|---|---|---|
| HANDLE | void* | 在 32 位 Windows 操作系统上为 32 位,在 64 位 Windows 操作系统上为 64 位。 | |
| BYTE | unsigned char | 8 位 | |
| SHORT | short | 16 位 | |
| WORD | unsigned short | 16 位 | |
| INT | int | 32 位 | |
| UINT | unsigned int | 32 位 | |
| LONG | long | 32 位 | |
| BOOL | long | 32 位 | |
| DWORD | unsigned long | 32 位 | |
| ULONG | unsigned long | 32 位 | |
| CHAR | char | 用 ANSI 修饰。 | |
| LPSTR | char* | 或 | 用 ANSI 修饰。 |
| LPCSTR | Const char* | 或 | 用 ANSI 修饰。 |
| LPWSTR | wchar_t* | 或 | 用 Unicode 修饰。 |
| LPCWSTR | Const wchar_t* | 或 | 用 Unicode 修饰。 |
| FLOAT | Float | 32 位 | |
| DOUBLE | Double | 64 位 |
下表将说明 Win32 API 中几个常用的 DLL。
| DLL | 内容说明 |
|---|---|
| GDI32.dll | 用于设备输出的图形设备接口 (GDI) 函数,例如用于绘图和字体管理的函数。 |
| Kernel32.dll | 用于内存管理和资源处理的低级别操作系统函数。 |
| User32.dll | 用于消息处理、计时器、菜单和通信的 Windows 管理函数。 |
win32API提供的多媒体API叫MCI,在system32目录下的winmm.dll中包含了该函数。
本文探讨了在C/S架构下实现口语考试系统的方法,重点介绍了如何通过DllImport调用Win32 API,并给出了具体的代码示例。同时,列举了非托管与托管代码间的数据类型转换,以及常用Win32 API DLL的介绍。
1049

被折叠的 条评论
为什么被折叠?



