Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use IntPtr of c #

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is mainly about "how to use IntPtr of c #". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to use IntPtr of c #"!

In ccalldll2.cpp:

Int retstruct (user* uther int xm int y)

{

U-> id + = 10 + x

U-> age + = 10 + y

Return 0

}

In c#:

[DllImport ("ccalldll2.dll", EntryPoint = "retstruct", CallingConvention=CallingConvention.Cdecl)]

Public static extern int retstruct (IntPtr ptrUser, int x, int y); / / only ccalldll2 is referenced in the reference, and ccalldll2 uses cSharpDLLforJNA. Is that a problem?

[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

/ / first, memory space is allocated through Marshal, and unmanaged space is allocated according to the size of user.

Int size = Marshal.SizeOf (u); / / for value types, Sizeof (variable), and for reference types, Sizeof (typeof (TYPE))

IntPtr ptruser = Marshal.AllocHGlobal (size); / / allocate memory

/ / copy the value of u to ptruser space

Marshal.StructureToPtr (u, ptruser, false)

Int res = retstruct (ptruser, 5,5); / / call the function retstruct in DLL to handle the id and age in the user referred to by the ptruser pointer.

User U2 = (user) Marshal.PtrToStructure (ptruser, typeof (user)); / / convert the processed ptruser to user

Console.WriteLine (u2.id + ":" + u2.age)

Console.WriteLine (res+ ":" + u.id + ":" + u.age)

Marshal.FreeHGlobal (ptruser)

}

Display the results:

20:22

0:5:7

At this point, I believe you have a deeper understanding of "how to use the IntPtr of c #". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report