andrewrk
andrewrk

Reputation: 31162

How do I get an IntPtr pointing to an Integer in VB.NET?

I need to get the address of an integer and assign it to an IntPtr to use in an 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 do I do?

Upvotes: 4

Views: 15940

Answers (4)

Skillaura13
Skillaura13

Reputation: 5

I might be completely wrong, but have you tried this?

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

Upvotes: 0

andrewrk
andrewrk

Reputation: 31162

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)

Upvotes: 2

Gregory Higley
Gregory Higley

Reputation: 16588

Short answer: you can't and you don't need to. (Although there is a way to do so in C#.)

But there are other ways to do this. When you declare the 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 VB.NET's syntax for this, so my apologies. Here's the declaration and use of APICall in C#. Something very closely similar would have to be done in VB.NET:

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

int x = 3;
APICall(ref x);

In sum, whether it's C# or VB.NET, it's all about how you declare APICall, not about getting the address of the integer.

Upvotes: 3

Ash
Ash

Reputation: 62116

The Marshal class is probably what you need. This article (may be getting a bit out of date now) provides some good examples.

However, I would read the other answer by Gregory that talks about declaring the external function and try to do it that way first. Using Marshal should be a last resort.

Upvotes: 3

Related Questions