c# - 在 C# 中访问 C++ 结构体

标签 c#

我有一个 VC++结构如

struct VideoInputV20 {
   int m_nBrightness;
   int m_nSharpness;
   int m_nSaturation;
   int m_nContrast;
   int m_nInputState;
   CString m_sObjref;
};

在 C# 中,我将在 byte[] 中接收该结构。这里我需要将byte[]转换为stuct。

我怎样才能实现这个目标?如果可能,请提供示例代码。

最佳答案

在 C# 中声明您的结构:

[StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)]  
struct VideoInputV20
{
    int m_nBrightness;
    int m_nSharpness;
    int m_nSaturation;
    int m_nContrast;
    int m_nInputState;
    [MarshalAs(UnmanagedType.LPWStr)]
    string m_sObjref;
}

然后是从 byte[] 中取出它的代码

GCHandle handle = new GCHandle();
try
{
    // Pin the byte[]
    handle = GCHandle.Alloc(yourByteArray, GCHandleType.Pinned);
    IntPtr ptr = handle.AddrOfPinnedObject();

    // Marshal byte[] into struct instance
    VideoInputV20 myVideoInputV20 = (VideoInputV20 )Marshal.PtrToStructure(ptr, typeof(VideoInputV20 ));
}
// Clean up memory
finally
{
    if (handle.IsAllocated) handle.Free();
}

关于c# - 在 C# 中访问 C++ 结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1687294/

相关文章:

c# - 尾递归优化发生在 visual studio 10 x64 调试中但不是在发布中?

c# - 如何删除 HttpClient 请求 header C# 中的默认字符集

c# - 确定类 x 是否派生自类 y 的最简单方法? (C#)

c# - 什么是适用于 C# 的良好 Twitter SDK?

C# Avi 文件 : fccHandler -> codec name?

c# - 具有多个/未知条件的动态 linq 查询

c# - 遍历 html 字符串以查找所有 img 标签并替换 src 属性值

c# - css 将两个输入置于一个 div 中

c# - 如何在 C# 中使用 C-Library

c# - 单击按钮时如何在文本框中显示不同的sql数据