c# - PInvoke 在类定义中不起作用

标签 c# pinvoke

我有一个问题,很奇怪。 当我在 PInvoke 中使用下一个结构时,它正在工作,但是当我将其更改为类时,它不起作用。

我的c#:

[StructLayout(LayoutKind.Sequential)]
public struct SPInvokeImage
{          
    public int m_BitsPerPixel;  // 8,16,24,32 
    public int m_ImageHeight;
    public int m_ImageWidth;
    public int m_BytesArraySize; // array size in bytes. 

    public IntPtr m_pArray; //data array 
}

c++

   typedef struct 
   {          
 int mBitsPerPixel;  // 8,16,24,32 
 int mImageHeight;
 int mImageWidth;
 int BytesArraySize; // array size in bytes. 

 uint8_t *Array;        //data array 
   }SPInvokeImage;

当我将 C# 更改为这样时,它会停止工作:

 [StructLayout(LayoutKind.Sequential)]
 public class SPInvokeImage
 {          
     public int m_BitsPerPixel;  // 8,16,24,32 
     public int m_ImageHeight;
     public int m_ImageWidth;
     public int m_BytesArraySize; // array size in bytes. 

     public IntPtr m_pArray; //data array 
 }

最佳答案

这是因为当您切换到类时,对象会通过引用而不是像 struct 那样通过值传递到 native 代码。因此,存在额外的间接级别。您需要在 pinvoke 声明中删除该间接级别。您目前可能正在使用 ref 进行传递。当您从 struct 切换到 class 时,只需删除 ref 即可。

关于c# - PInvoke 在类定义中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9771337/

相关文章:

c# - 使用 Polly 时抛出特定异常

c# - 动态定义类型化数据集?

c# - C Dll 导入在 C# 中引发 Marshall 指令异常

c# - 编码(marshal) Win32 结构时的安全句柄 (PROCESS_INFORMATION)

c# - 将 C++ 字符串 vector 编码到 C#

c# - Microsoft Visual Studio C# 安装程序

c# - .NET 迁移 : Setup and migrate multiple databases at runtime

c# - 将 C 结构编码到 C#

c# - ASP.NET 自动注销

c# - 获取桌面/外壳窗口的句柄