Created
August 1, 2016 07:16
-
-
Save aliyome/cabc5470d32e655341eb7aa3a5637221 to your computer and use it in GitHub Desktop.
GCHandleとMarshalについて迷ったらこれ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Imports System.Runtime.InteropServices | |
| Module Module1 | |
| ' int hoge(int val) { return val; } | |
| <DllImport("ConsoleApplication2.dll", CallingConvention:=CallingConvention.Cdecl)> | |
| Public Function hoge(val As Int32) As Int32 | |
| End Function | |
| ' int foo(int* val) { *val = *val + 200; return val; } | |
| <DllImport("ConsoleApplication2.dll", CallingConvention:=CallingConvention.Cdecl)> | |
| Public Function foo(val As IntPtr) As IntPtr | |
| End Function | |
| ' int bar(int* val) { **val = 900; return val; } | |
| <DllImport("ConsoleApplication2.dll", CallingConvention:=CallingConvention.Cdecl)> | |
| Public Function bar(val As IntPtr) As IntPtr | |
| End Function | |
| Sub Main() | |
| ' intをalloc | |
| Dim gchFoo As GCHandle = GCHandle.Alloc(0, GCHandleType.Pinned) | |
| gchFoo.Target = 200 | |
| Console.WriteLine(hoge(10)) | |
| ' int*を渡す | |
| Dim retFoo As IntPtr = foo(gchFoo.AddrOfPinnedObject) | |
| Dim dstFoo(0) As Integer | |
| ' 戻り値retを*retとしてdstFooにコピー | |
| Marshal.Copy(retFoo, dstFoo, 0, 1) | |
| ' int** bar | |
| Dim gchBar As GCHandle = GCHandle.Alloc(gchFoo.AddrOfPinnedObject, GCHandleType.Pinned) | |
| ' int**を渡す | |
| Dim retBar As IntPtr = bar(gchBar.AddrOfPinnedObject) | |
| Dim dstBar(0) As IntPtr | |
| Dim dstBarPtr(0) As Int32 | |
| ' int**をint*にしてdstBarにコピー | |
| Marshal.Copy(retBar, dstBar, 0, 1) | |
| ' int*をintにしてdstBarPtrにコピー | |
| Marshal.Copy(dstBar(0), dstBarPtr, 0, 1) | |
| Console.ReadLine() | |
| gchFoo.Free() | |
| End Sub | |
| End Module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment