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。