C#調用DLL複雜函數結構體

現在公司要做一個使用C#程序調用C++的一個DLL庫,解析文件的功能。所以在網上找了一些資料。


    一、結構體傳遞

  1. #define JNAAPI extern "C" __declspec(dllexport) // C方式導出函數  
  2.   
  3. typedef struct      
  4. {    
  5.     int osVersion;    
  6.     int majorVersion;    
  7.     int minorVersion;    
  8.     int buildNum;    
  9.     int platFormId;    
  10.     char szVersion[128];    
  11. }OSINFO;    
  12.   
  13. // 1. 獲取版本信息(傳遞結構體指針)    
  14. JNAAPI bool GetVersionPtr( OSINFO *info );    
  15. // 2.獲取版本信息(傳遞結構體引用)    
  16. JNAAPI bool GetVersionRef(OSINFO &info);    
#define JNAAPI extern "C" __declspec(dllexport) // C方式導出函數

typedef struct    
{  
    int osVersion;  
    int majorVersion;  
    int minorVersion;  
    int buildNum;  
    int platFormId;  
    char szVersion[128];  
}OSINFO;  

// 1. 獲取版本信息(傳遞結構體指針)  
JNAAPI bool GetVersionPtr( OSINFO *info );  
// 2.獲取版本信息(傳遞結構體引用)  
JNAAPI bool GetVersionRef(OSINFO &info);  

可以通過二種方式進行調用:

  1. // OSINFO定義  
  2. [StructLayout(LayoutKind.Sequential)]  
  3. public struct OSINFO  
  4. {  
  5.     public int osVersion;  
  6.     public int majorVersion;  
  7.     public int minorVersion;  
  8.     public int buildNum;  
  9.     public int platFormId;  
  10.     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]  
  11.     public string szVersion;  
  12. }  
// OSINFO定義
[StructLayout(LayoutKind.Sequential)]
public struct OSINFO
{
	public int osVersion;
	public int majorVersion;
	public int minorVersion;
	public int buildNum;
	public int platFormId;
	[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
	public string szVersion;
}

1. 方式一(傳入結構體引用),在C#中,結構體是以傳值方式傳遞,類纔是以傳地址方式傳遞,加關鍵字ref即可. C端傳遞了兩種不同類型的參數,都可以通過引用來解決.

  1. [DllImport("jnalib.dll", EntryPoint = "GetVersionPtr")]  
  2. public static extern bool GetVersionPtr(ref OSINFO info);  
  3. public static extern bool GetVersionRef(ref OSINFO info);  
[DllImport("jnalib.dll", EntryPoint = "GetVersionPtr")]
public static extern bool GetVersionPtr(ref OSINFO info);
public static extern bool GetVersionRef(ref OSINFO info);

2. 方式二(傳入IntPtr(平臺通用指針))

  1. IntPtr pv = Marshal.AllocHGlobal(148); //結構體在使用時一定要分配空間(4*sizeof(int)+128)  
  2. Marshal.WriteInt32(pv,148); //向內存塊裏寫入數值  
  3. if (GetVersionPtr(pv)) //直接以非託管內存塊地址爲參數  
  4. {  
  5.     Console.WriteLine("--osVersion:{0}", Marshal.ReadInt32(pv, 0));  
  6.     Console.WriteLine("--Major:{0}",Marshal.ReadInt32(pv, 4)); //移動4個字節  
  7.     Console.WriteLine("--BuildNum: " + Marshal.ReadInt32(pv, 12));  
  8.     Console.WriteLine("--szVersion: "+Marshal.PtrToStringAnsi((IntPtr)(pv.ToInt32()+20)));  
  9. }  
  10. Marshal.FreeHGlobal(pv); //處理完記得釋放內存  
IntPtr pv = Marshal.AllocHGlobal(148); //結構體在使用時一定要分配空間(4*sizeof(int)+128)
Marshal.WriteInt32(pv,148); //向內存塊裏寫入數值
if (GetVersionPtr(pv)) //直接以非託管內存塊地址爲參數
{
	Console.WriteLine("--osVersion:{0}", Marshal.ReadInt32(pv, 0));
	Console.WriteLine("--Major:{0}",Marshal.ReadInt32(pv, 4)); //移動4個字節
	Console.WriteLine("--BuildNum: " + Marshal.ReadInt32(pv, 12));
	Console.WriteLine("--szVersion: "+Marshal.PtrToStringAnsi((IntPtr)(pv.ToInt32()+20)));
}
Marshal.FreeHGlobal(pv); //處理完記得釋放內存

 二.結構體數組的傳遞

  1. // 傳遞結構體指針  
  2. JNAAPI bool GetVersionArray(OSINFO *info,int nLen);  
// 傳遞結構體指針
JNAAPI bool GetVersionArray(OSINFO *info,int nLen);

調用:

  1. /** 
  2.  * C#接口,對於包含數組類型,只能傳遞IntPtr 
  3.  */   
  4. [DllImport("jnalib.dll", EntryPoint = "GetVersionArray")]  
  5. public static extern bool GetVersionArray(IntPtr p, int nLen);    
  6.   
  7. // 源目標參數  
  8. OSINFO[] infos = new OSINFO[2];  
  9. for (int i = 0; i < infos.Length; i++)  
  10. {  
  11.     infos[i] = new OSINFO();  
  12. }  
  13.   
  14. IntPtr[] ptArr = new IntPtr[1];  
  15. ptArr[0] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(OSINFO)) * 2); //分配包含兩個元素的數組  
  16. IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(OSINFO)));   
  17. Marshal.Copy(ptArr, 0, pt, 1); //拷貝指針數組  
  18. GetVersionArray(pt, 2); //調用  
  19.   
  20. //還原成結構體數組  
  21. for (int i = 0; i < 2; i++)    
  22. {  
  23.     infos[i]=(OSINFO)Marshal.PtrToStructure((IntPtr)(pt.ToInt32()+i*Marshal.SizeOf(typeof(OSINFO))),typeof(OSINFO));  
  24.     Console.WriteLine("OsVersion:{0} szVersion:{1}", infos[i].osVersion, infos[i].szVersion);  
  25. }  
/**
 * C#接口,對於包含數組類型,只能傳遞IntPtr
 */ 
[DllImport("jnalib.dll", EntryPoint = "GetVersionArray")]
public static extern bool GetVersionArray(IntPtr p, int nLen);  

// 源目標參數
OSINFO[] infos = new OSINFO[2];
for (int i = 0; i < infos.Length; i++)
{
	infos[i] = new OSINFO();
}

IntPtr[] ptArr = new IntPtr[1];
ptArr[0] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(OSINFO)) * 2); //分配包含兩個元素的數組
IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(OSINFO))); 
Marshal.Copy(ptArr, 0, pt, 1); //拷貝指針數組
GetVersionArray(pt, 2); //調用

//還原成結構體數組
for (int i = 0; i < 2; i++)  
{
	infos[i]=(OSINFO)Marshal.PtrToStructure((IntPtr)(pt.ToInt32()+i*Marshal.SizeOf(typeof(OSINFO))),typeof(OSINFO));
	Console.WriteLine("OsVersion:{0} szVersion:{1}", infos[i].osVersion, infos[i].szVersion);
}

三. 複雜結構體的傳遞

 1. 輸出參數,結構體作爲指針傳出

  1. typedef struct  
  2. {  
  3.     char name[20];  
  4.     int age;  
  5.     double scores[30];  
  6. }Student;  
  7.   
  8. // Class中包含結構體數組類型  
  9. typedef struct  
  10. {  
  11.     int number;  
  12.     Student students[50];  
  13. }Class;  
  14.   
  15. // 傳入複雜結構體測試  
  16. JNAAPI int GetClass(Class *pClass,int len);  
typedef struct
{
	char name[20];
	int age;
	double scores[30];
}Student;

// Class中包含結構體數組類型
typedef struct
{
	int number;
	Student students[50];
}Class;

// 傳入複雜結構體測試
JNAAPI int GetClass(Class *pClass,int len);

  1. // 接口定義   
  2. [DllImport("jnalib.dll", EntryPoint = "GetClass")]  
  3. public static extern int GetClass(IntPtr pv,int len);  
  4.   
  5. // 結構體定義  
  6. // Student  
  7. [StructLayout(LayoutKind.Sequential)]  
  8. public struct Student  
  9. {  
  10.     [MarshalAs(UnmanagedType.ByValTStr,SizeConst=20)]  
  11.     public string name;  
  12.     public int age;  
  13.     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]  
  14.     public double[] scores;  
  15. }  
  16.   
  17. // Class  
  18. [StructLayout(LayoutKind.Sequential)]  
  19. public struct Class  
  20. {  
  21.     public int number;  
  22.     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)] // 指定數組尺寸   
  23.     public Student[] students; // 結構體數組定義  
  24. }  
  25.   
  26. // 調用複雜結構體測試  
  27. int size = Marshal.SizeOf(typeof(Class)) * 50;  
  28. IntPtr pBuff = Marshal.AllocHGlobal(size); // 直接分配50個元素的空間,比Marshal.copy方便多了  
  29. GetClass(pBuff, 50);  
  30.   
  31. Class[] pClass = new Class[50];  
  32. for (int i = 0; i < 50; i++)  
  33. {  
  34.     IntPtr ptr = new IntPtr(pBuff.ToInt64() + Marshal.SizeOf(typeof(Class)) * i);  
  35.     pClass[i] = (Class)Marshal.PtrToStructure(ptr, typeof(Class));  
  36. }  
  37. Marshal.FreeHGlobal(pBuff); // 釋放內存  
// 接口定義 
[DllImport("jnalib.dll", EntryPoint = "GetClass")]
public static extern int GetClass(IntPtr pv,int len);

// 結構體定義
// Student
[StructLayout(LayoutKind.Sequential)]
public struct Student
{
	[MarshalAs(UnmanagedType.ByValTStr,SizeConst=20)]
	public string name;
	public int age;
	[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]
	public double[] scores;
}

// Class
[StructLayout(LayoutKind.Sequential)]
public struct Class
{
	public int number;
	[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)] // 指定數組尺寸 
	public Student[] students; // 結構體數組定義
}

// 調用複雜結構體測試
int size = Marshal.SizeOf(typeof(Class)) * 50;
IntPtr pBuff = Marshal.AllocHGlobal(size); // 直接分配50個元素的空間,比Marshal.copy方便多了
GetClass(pBuff, 50);

Class[] pClass = new Class[50];
for (int i = 0; i < 50; i++)
{
	IntPtr ptr = new IntPtr(pBuff.ToInt64() + Marshal.SizeOf(typeof(Class)) * i);
	pClass[i] = (Class)Marshal.PtrToStructure(ptr, typeof(Class));
}
Marshal.FreeHGlobal(pBuff); // 釋放內存

2. 輸入參數, 給複雜結構體賦值後作爲輸入參數傳入

   對於比較大的結構體指針,無法直接應用結構體類型,轉化成IntPtr類型, 此時需要將原生類型轉化爲指針,並給指針賦值

   調用方法: Marshal.StructureToPtr(stu, ptr1, true) 

end...

轉自:http://tcspecial.iteye.com

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章