DotNet - What is int*?

前端 未结 3 1857
执念已碎
执念已碎 2021-01-11 14:56

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

相关标签:
3条回答
  • 2021-01-11 15:24

    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.

    0 讨论(0)
  • 2021-01-11 15:38

    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#.

    • Unsafe contexts
    • Pointer Types
    • Fixed and movable variables
    • Pointer conversions
    • Pointers in expressions
    • The 'fixed' statement
    • Stack allocation
    • Dynamic memory allocation
    0 讨论(0)
  • 2021-01-11 15:39

    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
     //...
    
    0 讨论(0)
提交回复
热议问题