浅析使用MarshalAsAttribute 类在托管代码和非托管代码之间封送数据

MarshalAsAttribute 类

命名空间: System.Runtime.InteropServices
程序集: mscorlib(在 mscorlib.dll 中)

using System;
using System.Text;
using System.Runtime.InteropServices;

使用场合:

class Program
{

//Applied to a parameter.
public void M1([MarshalAs(UnmanagedType.LPWStr)]String msg) {}

//Applied to a field within a class.
class MsgText {
[MarshalAs(UnmanagedType.LPWStr)]
public String msg = “Hello World”;
}

//Applied to a return value.
[return: MarshalAs(UnmanagedType.LPWStr)]
public String GetMessage()
{
return “Hello World”;
}

static void Main(string[] args)
{ }
}

一个例子:
(MFC导出函数及结构体声明)
extern “C”_declspec(dllexport) BOOL WINAPI Task_AddPatient(CTask* pTask, PatientParam* mPat);

struct PatientParam
{
unsigned int nPatientId; //病历号
unsigned int nAge; unsigned int nSex; //性别
unsigned char szName[20]; //姓名
unsigned char szTel[50]; //电话
};

(WPF对应函数及结构体声明)
[DllImport(“HTask.dll”)]
public static extern bool Task_AddPatient(int pTask, ref PatientParam mPat);

[StructLayout(LayoutKind.Sequential)]
public struct PatientParam
{
public uint nPatientId; //病历号
public uint nSex; //性别
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public Byte[] szName; //姓名
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public char[] szTel; //电话
}

UnmanagedType有很多类型,这里使用的是从MFC向WPF传递字符数组的例子,在结构体声明之前添加的[StructLayout(LayoutKind.Sequential)]语句表示允许控制类或结构的数据字段的物理布局。通常,公共语言运行时控制类或结构的数据字段在托管内存中的物理布局。但是,如果您希望以某种方法排列类或结构需要,便可以使用 StructLayoutAttribute。

你可能感兴趣的:(数据传递,托管与非托管代码)