How to use IntPtr of c #
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!