Like I said, why don't you cache the string like this :
This only does the UDP call once.Code:void __stdcall GetString(LPSTR szString, int *pnLength) { static CString sString; if (szString == NULL) { sString = GetStringFromUdp(); *pnLength = sString.GetLength(); } else { const int nToCopy = min(*pnLength, sString.GetLength()); ::strncpy(szString, sString, nToCopy); *pnLength = nToCopy; } }
Not particularly nice though, it'll screw up if you ever wanted to make your app multithreaded : I'd prefer methods of the following kind :
Of course the real nice way of doing it is to use COM - but the above will suffice I would suggest.Code:void * __stdcall InitialiseCallResult() { CString *psString = new CString; *psString = GetFromUdp(); return psString; } void __stdcall GetCallResult(void *pString, LPSTR szString, int *pnLength) { CString *psString = (CString *)pString; if (szString == NULL) { *pnLength = psString->GetLength(); } else { const int nToCopy = min(*pnLength, psString->GetLength()); ::strncpy(szString, *psString, nToCopy); *pnLength = nToCopy; } } void __stdcall ReleaseCallResult(void *pString) { CString *psString = (CString *)pString; delete psString; } // C# // C# public class Interop { [DllImport("MyDll.dll")] static private extern IntPtr InitialiseCallResult(); [DllImport("MyDll.dll")] static private unsafe extern void GetCallResult(IntPtr pHandle, byte *pbData, ref int pnLength); [DllImport("MyDll.dll")] static private extern void ReleaseCallResult(); static public string GetString() { IntPtr pHandle = InitialiseCallResult(); int nLength = 0; GetCallResult(pHandle, null, ref nLength); byte [] abData = new byte[nLength]; fixed (byte *pbData = abData) { GetCallResult(pHandle, pbData, ref nLength); } ReleaseCallResult(pHandle); } }
Darwen.




Reply With Quote