本篇內(nèi)容主要講解“如何使用c#的IntPtr”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“如何使用c#的IntPtr”吧!
ccalldll2.cpp中:
int retstruct(user* u,int x,int y)
{
u->id += 10 + x;
u->age += 10 + y;
return 0;
}
在c#中:
[DllImport("ccalldll2.dll", EntryPoint = "retstruct",CallingConvention=CallingConvention.Cdecl)]
public static extern int retstruct(IntPtr ptrUser, int x, int y); //在引用中只引用了ccalldll2,而ccalldll2又用到了cSharpDLLforJNA,這樣有問題嗎
[StructLayout(LayoutKind.Sequential)]
struct user
{
public int id;
public int age;
};
private void btnInptr_Click(object sender, EventArgs e)
{
user u = new user();
u.id = 5;
u.age = 7;
//先要通過Marshal來分配內(nèi)存空間,根據(jù)user的大小進行分配非托管空間大小
int size = Marshal.SizeOf(u);//對于值類型,可以Sizeof(變量),對于引用類型則Sizeof(typeof(TYPE))
IntPtr ptruser = Marshal.AllocHGlobal(size);//分配內(nèi)存
//將u的值copy到ptruser空間
Marshal.StructureToPtr(u, ptruser, false);
int res = retstruct(ptruser, 5, 5);//調(diào)用DLL中函數(shù) retstruct中將對ptruser指針?biāo)傅膗ser中的id和age處理
user u2 = (user)Marshal.PtrToStructure(ptruser, typeof(user));//將處理之后的ptruser再轉(zhuǎn)換為user
Console.WriteLine(u2.id + ":" + u2.age);
Console.WriteLine(res+":"+u.id+":"+u.age);
Marshal.FreeHGlobal(ptruser);
}
顯示結(jié)果:
20:22
0:5:7
到此,相信大家對“如何使用c#的IntPtr”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。