Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 433
andrewrk Avatar asked Feb 28 '23 11:02

andrewrk


2 Answers

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.

like image 79
Ash Avatar answered Mar 03 '23 00:03

Ash


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.

like image 25
Gregory Higley Avatar answered Mar 03 '23 01:03

Gregory Higley