C# 调用非托管代码:"Cannot convert from 'CustomClass' to 'ref System.IntPtr'"



我正在为c#中的c++库编写包装函数。我在c++中的函数使用两个指针作为参数,它会更改其中一个指针指向的内容(foo)。所以在c#中,我需要将其作为ref传递,对吗?我有:

C++:

ErrorCode MyFunction(void* dev, void* foo);

C#:

[DllImport("MyLib.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        public static extern ExceptionClass.ErrorCode MyFunction(IntPtr dev, ref IntPtr foo);

当我像这个一样调用C#中的函数时

public void CallFunction(DevClass dev, FooClass foo)
{
  MyFunction(dev, ref foo);
}

我得到错误

Error 3 Argument 2: cannot convert from 'ref FooClass' to 'ref System.IntPtr'

我认为您不必为第二个参数foo设置ref

根据MSDN

IntPtr类型可由支持指针的语言使用在do和do语言之间引用数据的常用方法不支持指针。

因此,IntPtr就像一个指针,你可以修改它指向的数据。

最新更新