移植的C结构到C# [英] Porting C struct to C#

查看:213
本文介绍了移植的C结构到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我移植的C代码到C#和我有一些疑问。

I'm Porting C code to C# and I have some doubts.

考虑这个结构:

typedef struct
{
  uint32_t       w;
  uint32_t       h;
  uint32_t       f_cc;
  uint32_t       st;
  unsigned char *pl[4];
  int32_t        strd[4];
  void         (*done)(void *thisobj);
  void          *e_cc;
  uint32_t       rsrvd2;
  uint32_t       rsrvd3;
} f_tt;



我已经做到这一点,它不工作(可能是因为它是错的: - /):

I've done this and it does not work (probably because it's wrong :-/ ):

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct f_tt
{
    public uint w;
    public uint h;
    public uint f_cc;
    public uint st;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public Byte[] pl;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public int[] strd;
    public delegate void done(IntPtr thisobj);
    public delegate void e_cc();
    public uint rsrvd2;
    public uint rsrvd3;
}



有人能告诉我如何做到这一点的IC#?

Can someone advise me how to do this i c#?

  void         (*done)(void *thisobj);
  void          *e_cc;

感谢您!

推荐答案

在我们来的代表,我怀疑你是错收拾结构。这是非常不寻常的这样做。只有这样做,如果你发现在C代码包的#pragma

Before we come to the delegates, I suspect that you are wrong to pack the struct. It's very unusual to do so. Only do that if you find the pack #pragma in the C code.

e_cc 字段是不是一个函数指针。这只是一个空指针。在C#也就是的IntPtr

The e_cc field is not a function pointer. It's just a void pointer. In C# that is IntPtr.

PL 成员是4的指针数组。我不太清楚它们包含的内容,但是可以肯定,你可以封送这样的:

The pl member is an array of 4 pointers. I'm not quite sure what they contain, but for sure you can marshal that like this:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public IntPtr[] pl;

这给你留下人工干预来填充阵列或阅读其内容。这有可能是可以由编组完成,但不知道互操作的语义,我不能说该怎么做。

That leaves you with manual intervention to populate the array, or read its contents. It's possible that could be done by the marshaller, but without knowing the semantics of the interop, I can't say how to do that.

至于完成,你应该声明结构之外的委托。像这样的:

As for done, you should declare the delegate outside the struct. Like this:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void doneDelegate(IntPtr thisobj);



在这里,我假设调用约定是 CDECL ,因为没有什么在C代码,否则说。

Here I am assuming that the calling convention is cdecl since there's nothing in the C code to say otherwise.

全部放在一起你有:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void doneFunc(IntPtr thisobj);

[StructLayout(LayoutKind.Sequential)]
public struct f_tt
{
    public uint w;
    public uint h;
    public uint f_cc;
    public uint st;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public IntPtr[] pl;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public int[] strd;
    public doneDelegate done;
    public IntPtr e_cc;
    public uint rsrvd2;
    public uint rsrvd3;
}

这篇关于移植的C结构到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆