C#调用C封装dll结构体指针
原来一直用MFC做,最近项目要用C#学了学基本的东西还是有差距啊,调用底层函数的时候卡主了,求路过大神帮忙
先是C++的定义:
typedef struct TagData_struct{
double value; //返回点的数值
long time; //返回点的时间,秒
int status; //返回点的状态
}TagData;
初始化:
char *tagNames[MEM_PAGE_ITEMS];
for ( int i=0; i<MEM_PAGE_ITEMS; i++ )
{
tagNames[i]=(char*)malloc( TAGNAME_LENGTH*sizeof(char) );
memset(tagNames[i],0,TAGNAME_LENGTH);
strcpy( tagNames[i], PtName[i].GetBuffer());
PtName[i].ReleaseBuffer();
}
TagData *g_pTagData;
g_pTagData =(TagData *)malloc( MEM_PAGE_ITEMS*sizeof(TagData) );
memset( g_pTagData, 0, MEM_PAGE_ITEMS*sizeof(TagData) );
调用:
iRet =RTDBDao.GetRTDataByBatch( tagNames , g_pTagData, g_iPtCount );
函数原型:
int GetRTDataByBatch( char* tagNames[],TagData * pTagData,long nCount )
下面是我写的C#的:
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TagData
{
public double value; //返回点的数值
public long time; //返回点的时间,秒
public int status; //返回点的状态
};
class LibWrapper
{
[DllImport("DataInterface.dll", CharSet = CharSet.Ansi, EntryPoint = "GetRTDataByBatch", CallingConvention = CallingConvention.Cdecl)]
public extern static int GetRTDataByBatch([In] string[] tagName, IntPtr tgs, long nCount);
}
main函数中:
string[] tagNames = new string[2];
tagNames[0] = "Dev_Test00";
tagNames[1] = "Dev_Test01";
IntPtr[] ptArray = new IntPtr[1];
ptArray[0] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TagData)) * 10);
IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * 1);
Marshal.Copy(ptArray, 0, pt, 1);
iRet = LibWrapper.GetRTDataByBatch(tagNames, pt, 2);
for (int i = 0; i < 2; i++)
{
TagData tagInfo = (TagData)Marshal.PtrToStructure((IntPtr)((UInt32)ptArray[0] + i * Marshal.SizeOf(typeof(TagData))), typeof(TagData));
double val = tagInfo.value;
long tm = tagInfo.time;
int state = tagInfo.status;
}
Marshal.FreeHGlobal(ptArray[0]);
Marshal.FreeHGlobal(pt);
取不到数据为什么呢? 哪里写错了?