昨夜飘风
昨 夜, 风, 飘 过; 枯 树, 叶, 飞 落。
第一个是C#程序;第二个是测试用的dll,没有头文件但已经导出了一个函数。两个代码都可以直接编译。

C# code
using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct NSP { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string serverAddress; public Int16 numLicAvail; } class Program { [DllImport("MyDll.dll")] static extern int EnumServer( byte[] nsps, // <--- just marshaled as byte array ref int size); static void Main(string[] args) { int sizeArray = 4; int sizeNSP = Marshal.SizeOf(typeof(NSP)); // // allocate storage and PInvoke // byte[] buf = new byte[4 * sizeNSP]; int result = EnumServer(buf, ref sizeArray); // // get results, using Marshal class to unpack // GCHandle pinned = GCHandle.Alloc(buf, GCHandleType.Pinned); for(int i=0; i<sizeArray; i++) { IntPtr ptr = new IntPtr(pinned.AddrOfPinnedObject().ToInt64() + i * sizeNSP); NSP nsp = (NSP) Marshal.PtrToStructure(ptr, typeof(NSP)); Console.WriteLine(nsp.serverAddress + ": " + nsp.numLicAvail); } pinned.Free(); Console.ReadLine(); } }


C/C++ code
// MyDll.cpp // #include <windows.h> typedef struct tag_nsproServerInfo{ char serverAddress[32]; short numLicAvail; }NSP; extern "C" { __declspec(dllexport) int EnumServer(NSP* pNSP, int* size) { strcpy(pNSP[0].serverAddress, "hello"); pNSP[0].numLicAvail = 888; strcpy(pNSP[1].serverAddress, "world"); pNSP[1].numLicAvail = 999; *size = 2; return 1234; } }
posted on 2008-04-16 08:53  昨夜飘风  阅读(326)  评论(0编辑  收藏  举报