日期:2014-05-17  浏览次数:21501 次

C++ 函数中参数是结构体,C#如何传参
C++函数定义如下:
C/C++ code
Result_t hhpReadConfigItem( int cfgType, int item,PVOID pStruct );

 typedef struct _tagHHP_VERSION_INFO
 {
        DWORD   dwStructSize;
        DWORD   dwMask;
        TCHAR   tcAPIRev[ MAX_VERSION_STRING_LEN ];             // SDK API version string
        TCHAR   tcFirmwareRev[ MAX_VERSION_STRING_LEN ];        // Imager firmware version
 } HHP_VERSION_INFO


C++中调用如下:
C/C++ code
HHP_VERSION_INFO version;
version.dwStructSize = sizeof(HHP_VERSION_INFO);
version.dwMask = SYM_MASK_ALL;//SYM_MASK_ALL = 0xffffffff
nResult = hhpReadConfigItem(1, 4, &version);//返回正确


C#这样定义有错吗
C# code
Result_t hhpReadConfigItem(int cfgType, int item, IntPtr pStruct);


C# code
public struct HHP_VERSION_INFO
        {
            public uint dwMask;
            public int dwStructSize;
            public string strAPIRev;
            public string strBootCodeRev;}

C#中要如何调用?
下面调用错在哪?
 
C# code
HHP_VERSION_INFO version = new HHP_VERSION_INFO();
            version.dwStructSize = 1704;
            version.dwMask = 4294967295;

            IntPtr pStuct =new IntPtr();
            pStuct = Marshal.AllocHGlobal(version.dwStructSize);
            //Marshal.StructureToPtr(version, pStuct, true);
            Result_t result = hhpReadConfigItem(1,4 , pStuct);//返回错误


------解决方案--------------------
定义错了,最少也得加返回值的类型吧?
------解决方案--------------------
你的结构体也要用Marshal规定长度和封装序列,参考
C# code

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
    public struct APSYDDataItem
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
        private string _securityID;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
        private string _ydtype;
    }