How to get IntPtr pointing to Integer in VB.NET?

I need to get the integer address and assign it to IntPtr for use in the API. How?

Dim my_integer as Integer
Dim ptr as new IntPtr

' This fails because AddressOf can only be used for functions.
ptr = AddressOf my_integer

APICall(ptr)

What should I do?

+3
source share
4 answers
Imports System.Runtime.InteropServices

Dim my_integer as Integer = 0
Dim ptr as IntPtr = Marshal.AllocHGlobal(4)

Marshal.WriteInt32(my_integer)

APICall(ptr)

my_integer = Marshal.ReadInt32(ptr)

Marshal.FreeHGlobal(ptr)
+2
source

Short answer: you cannot and you do not need. (Although there is a way to do this in C #.)

But there are other ways to do this. When you declare an external function APICall, you need to declare its parameter ByRef, and then just use it. The CLR will take care of getting the address.

I'm a C # guy and don't remember the VB.NET syntax for this, so my apologies. Here's the declaration and use APICallin C #. Something very closely similar should be done in VB.NET:

[DllImport("FooBar.dll")]
static extern APICall(ref int param);

int x = 3;
APICall(ref x);

, # VB.NET, , APICall, .

+3

The Marshal's class is probably what you need. This article (perhaps a bit outdated) contains some good examples.

However, I would read Gregory's other answer, which says to declare an external function and try to do it that way. Using a marshal should be a last resort.

+3
source

Maybe I'm wrong, but have you tried this?

Dim MyInt32 As Integer = 0
Dim MyPtr As IntPtr = MyInt32
0
source

Source: https://habr.com/ru/post/1713819/


All Articles