int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int length = 100000;
CEng * ceng = new CEng();
DWORD dwStart = GetTickCount();
for (int i = 0; i < length; i++) {
TENG eng;
ceng->Read(&eng, ceng->size, ceng->size * i);
eng.EngVal = i;
ceng->Write(&eng, ceng->size, (i*ceng->size));
if (i % 10000 == 0 || i == length - 1)
printf("正在读写的Eng.TagName:%s \n", eng.TagName);
}
printf("总条数%d,耗时:%d 毫秒 \n", length, GetTickCount() - dwStart);
// 验证数据
TENG eng5000;
ceng->Read(&eng5000, ceng->size, ceng->size * 5000);
printf("\n验证数据 \n");
printf("第5000个Eng的TagID:%d, EngVal:%lf \n", eng5000.TagID, eng5000.EngVal);
scanf_s("按任意键结束");
return 0;
}
7、还有写测试程序
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int length = 100000;
CEng * ceng = new CEng();
ceng->Create(ceng->size * length);
DWORD dwStart = GetTickCount();
for (int i = 0; i < length; i++)
{
TENG eng;
memset(&eng, 0, ceng->size);
eng.TagID = i;
sprintf_s(eng.AlarmCode, "AlarmCode.%d", i);
sprintf_s(eng.TagName, "TagName.%d", i);
if (i % 10000 == 0 || i == length - 1)
printf("正在写入的Eng.TagName:%s \n", eng.TagName);
ceng->Write(&eng, ceng->size, (i*ceng->size));
}
// print time
printf("写入数据完毕,总条数:%d\n", length);
printf("初始化值共享内存区耗时:%d 毫秒 \n", GetTickCount() - dwStart);
scanf_s("按任意键结束");
return 0;
}
8、当然得再贴一遍啦
五、差点忘记做成DLL了
1、定义外部函数
extern "C" __declspec(dllexport) int ReadFromSharedMemory(TENG *pData, int nSize, int offset)
{
return ceng->Read(pData, nSize, offset);
}
extern "C" __declspec(dllexport) int WriteToSharedMemory(void *pData, int nSize, int offset)
{
return ceng->Write(pData, nSize, offset);
}
2、好了,VC到此为止,可以去领盒饭了,c#进场
public class Lib
{
[DllImport("ConsoleApplication4.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ReadFromSharedMemory(IntPtr pData, int nSize, int offset);
[DllImport("ConsoleApplication4.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int WriteToSharedMemory(IntPtr pData, int nSize, int offset);
}
3、c#测试一下
static void Main(string[] args)
{
var length = 100000;
var startTime = DateTime.Now;
var size = Marshal.SizeOf(typeof(TEng));
var intPtrOut = Marshal.AllocHGlobal(size);
var intPtrIn = Marshal.AllocHGlobal(size);
for (var i = 0; i < length; i++)
{
Lib.ReadFromSharedMemory(intPtrOut, size, size * i);
var eng = Marshal.PtrToStructure<TEng>(intPtrOut);
eng.EngVal = i;
Marshal.StructureToPtr(eng, intPtrIn, true);
Lib.WriteToSharedMemory(intPtrIn, size, size * i);
if (i % 10000 == 0)
Console.WriteLine("eng.TagID:{0}", eng.TagID);
}
Console.WriteLine("总条数{0},耗时:{1} 毫秒", length.ToString(),
(DateTime.Now - startTime).TotalMilliseconds.ToString());
// 验证数据
var intPtr100 = Marshal.AllocHGlobal(size);
Lib.ReadFromSharedMemory(intPtr100, size, size * 100);
var eng100 = Marshal.PtrToStructure<TEng>(intPtr100);
Console.WriteLine();
Console.WriteLine("验证数据");
Console.WriteLine("第100个Eng的TagID:{0},EngVal:{1}", eng100.TagID, eng100.EngVal);
Console.ReadKey();
}