在 c# 中封送 c 结构 [英] Marshaling c structures in c#

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

问题描述

我有一个可以将结构作为输入的C"DLL",我必须从我的 c# 程序中调用该 dll

i have one 'C' 'DLL' which can take structures as input, i have to call that dll from my c# program

休耕是我在 c 中的示例结构,我必须在我的 c# 代码中编组这些结构

fallowing are the sample structures i have in c, i have to marshal those structures in my c# code

我做得对还是错?

typedef struct procedure
{
  char code[8];
}procedure;


typedef struct datefield
{
  char date[10];
}datefield;


typedef struct p45_clsgs
{
  procedure p45_clsg;
  datefield p45_clsgdte;
}p45_clsgs;

C#:

[StructLayout(LayoutKind.Sequential), Serializable]
struct procedure
{
//char code[];
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 8)]
public string code;
}
[StructLayout(LayoutKind.Sequential), Serializable]
struct datefield
{
//char date[10];
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 10)]
public string date;
}

struct p45_clsgs
{    
    public procedure p45_clsg;
    public datefield p45_clsgdte;
}

我的 C# 结构对于 C 结构是否正确?

Is my C# structs are correct for the C structs?

fallowing c 结构的等效 C# 结构是什么

What is the equivalent C# structure for the fallowing c structure

typedef struct p45_cldxed24
{
  procedure p45_cldxed[8];
}p45_cldxed24;

推荐答案

(Scratch my original answer)

你需要在每个结构的顶部有这个:

You need to have this at the top of each struct:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]

注意 CharSet 命名参数.这很重要,否则你最终会得到 wchar_t 数组而不是 char 数组.

Note the CharSet named parameter. That's important, or you'll end up with wchar_t arrays instead of char arrays.

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

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