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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With