一个简单的问题,我导入了一个DLL函数,参数是int*。
当我尝试输入 Method(0) 时,我收到一条错误消息:“int 和 int* 无法转换”。

那是什么意思?

最佳答案

这是 pointer to an int 的经典 C 符号。每当一个类型后跟 * 时,它表示该类型为 pointer 到该类型。在 C# 中,与 C 不同,除了在项目属性中启用 unsafe 代码之外,您还必须将函数显式定义为 unsafe 以使用指针。指针类型也不能直接与具体类型互换,因此必须首先获取类型的引用。要在 C#(或 C 和 C++)中获取指向其他类型的指针,例如 int,必须在要获取指针的变量前使用解引用运算符 &(与号):

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

'不安全' 代码 C#

下面是一些关于不安全代码和在 C# 中使用指针的关键文章。
  • Unsafe contexts
  • Pointer Types
  • Fixed and movable variables
  • Pointer conversions
  • Pointers in expressions
  • The 'fixed' statement
  • Stack allocation
  • Dynamic memory allocation
  • 关于c# - DotNet - 什么是 int*?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3238512/

    10-13 08:10
    查看更多