正确转换/编组C函数和DLL结构类型到C#

时间:2011-10-20 04:27:45

标签: c c#-4.0 interop marshalling

有人可以帮我把我的C结构/功能转换成C#吗?

我相信如果能够正确转换函数并正确编组我的结构,我可以正确调用DLL。

这是我的结构和使用它的函数:

typedef struct UIclient_info {
  char name[50];
  int age;
  SECONDUSER *stParent;
} FIRSTUSER;

typedef struct ui_product_form {    
  char m_sCoupon;
  double amountTotal;
  char m_sErrorCode[50];
  SUBPRODUCT *pstSubProduct;
} PRODUCT;

typedef struct tagReport
{
  REPORTSUMMARY *pstRepsum;
  char errorMsg[100];
} FINAL_REPORT;

int Save(FIRSTUSER *myUser, PRODUCT *uiStructure);
FINAL_REPORT GenerateReport(FIRSTUSER *myUser, PRODUCT *uiStructure);

1 个答案:

答案 0 :(得分:1)

这可能有效,也可能无效。你可以尝试一下,我不知道我是否正确处理了指针。我无法就此提供任何其他支持。如果它工作,那么它的工作原理。如果没有那么......哦,好吧。

//typedef struct UIclient_info {
//  char name[50];
//  int age;
//  SECONDUSER *stParent;
//} FIRSTUSER;

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct FirstUser
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=50)]
    public string Name;
    public int Age;
    [MarshalAs(UnmanagedType.LPStruct)]
    public IntPtr Parent;
}

//typedef struct ui_product_form {    
//  char m_sCoupon;
//  double amountTotal;
//  char m_sErrorCode[50];
//  SUBPRODUCT *pstSubProduct;
//} PRODUCT;

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct Product
{
    public char Coupon;
    public double AmountTotal;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=50)]
    public string ErrorCode;
    [MarshalAs(UnmanagedType.LPStruct)]
    public IntPtr SubProduct;
}

//typedef struct tagReport
//{
//  REPORTSUMMARY *pstRepsum;
//  char errorMsg[100];
//} FINAL_REPORT;

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct FinalReport
{
    [MarshalAs(UnmanagedType.LPStruct)]
    public IntPtr ReportSummary;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=100)]
    public string ErrorMsg;
}

static class MyLibraryHelper
{
    //int Save(FIRSTUSER *myUser, PRODUCT *uiStructure);

    [DllImport(@"MyLibrary.dll", CharSet=CharSet.Ansi)]
    internal static extern int Save(IntPtr myUser, IntPtr uiStructure);

    //FINAL_REPORT GenerateReport(FIRSTUSER *myUser, PRODUCT *uiStructure);

    [DllImport(@"MyLibrary.dll", CharSet=CharSet.Ansi)]
    internal static extern FinalReport GenerateReport(IntPtr myUser, IntPtr uiStructure);
}