tags:

views:

226

answers:

3

Hi,

simple question, I import a DLL function and the parameter are int*. When I try to enter Method(0), I get an error which says: "int and int* can not convert".

What is that meaning?

+6  A: 

It's a pointer to an int. Generally best avoided in managed code. You might want to post your imported method declaration. An IntPtr is usually sufficient for this kind of interop.

dkackman
It is just an argument that's passed by reference. It is well support by the P/Invoke marshaller, using IntPtr is a mistake.
Hans Passant
Depends what it does. If it's an array, `int[]` is what you want. If it's a handle, `IntPtr` usually is best, especially if you plan on passing 0. If you want an actual reference to an int, `ref int` or `out int` might work better.
Blindy
Without seeing the method declaration I wouldn't be able to guess one way or the other (ref vs array vs pointer). @Blindy is right on the money. Depends on the method being called. SendMessage's LPARAM for instance is usually marshalled as an IntPtr and that guy typically holds a memory pointer (which can be expressed as int*)
dkackman
+13  A: 

That is classic C notation for a pointer to an int. Whenever a type is followed by a *, it denotes that type as a pointer to that type. In C#, unlike in C, you must explicitly define functions as unsafe to use pointers, in addition to enabling unsafe code in your project properties. A pointer type is also not directly interchangeable with a concrete type, so the reference of a type must be taken first. To get a pointer to another type, such as an int, in C# (or C & C++ for that matter), you must use the dereference operator & (ampersand) in front of the variable you wish to get a pointer to:

unsafe
{
    int i = 5;
    int* p = &i;
    // Invoke with pointer to i
    Method(p);
}

'Unsafe' code C#

Below are some key articles on unsafe code and the use of pointers in C#.

jrista
Nate Bross
@Nate: Good point, I'll add a better explanation of the dereference operator.
jrista
Same comment here: it has nothing to do with unsafe code. The argument is simply passed by reference. The "ref" keyword in C#. It is a pointer in C# as well by the time the JIT compiler is done with it.
Hans Passant
@Hans: The question was "What is int*?". I was providing an answer to that question...not an answer about the semantics of passing variables in different ways.
jrista
+2  A: 

It depends on the language you use. In C#, you should declare the argument with the "ref" keyword. In VB.NET you should use the ByRef keyword. And you need to call it by passing a variable, not a constant. Something like this:

 int retval = 0;
 Method(ref retval);
 // Do something with retval
 //...
Hans Passant