February 25th, 2012, 08:22 AM
#1
C++ to C# Code Conversion problem
Hi All,
I am trying to convert the following C++ code to C#.
pExportDir = (PIMAGE_EXPORT_DIRECTORY)GetPtrFromRVA(exportsStartRVA, pNTHeader, pImageBase);
C# Syntax (Toggle Plain Text)
Code:
template <class T> LPVOID GetPtrFromRVA( DWORD rva, T* pNTHeader, PBYTE imageBase ) // 'T' = PIMAGE_NT_HEADERS
{
PIMAGE_SECTION_HEADER pSectionHdr;
INT delta;
INT delta2;
pSectionHdr = GetEnclosingSectionHeader( rva, pNTHeader );
if ( !pSectionHdr )
return 0;
delta = (INT)(pSectionHdr->VirtualAddress-pSectionHdr->PointerToRawData);
delta2 = (INT)( imageBase + rva - delta );
return (PVOID) ( imageBase + rva - delta );
}
The above function will return a "ExportDirectory" structure. Which is working fine in C++. I wrote the same function in C# like below
export_table = GetPtrFromRVA <IMAGE_EXPORT_DIRECTORY>(ExportTable_rva, _sectionHeaders[0], _dosHeader.e_magic);
C# Syntax (Toggle Plain Text)
Code:
public T GetPtrFromRVA<T>(UInt32 ExportTable_rva, IMAGE_SECTION_HEADER _sectionHeaders, UInt16 magic)
{
IMAGE_SECTION_HEADER textsectionHeader;
int delta;
textsectionHeader = GetEnclosingSectionHeader(ExportTable_rva, _sectionHeaders);
//if (textsectionHeader == null)
// return 0;
delta = (int)(_sectionHeaders.VirtualAddress - _sectionHeaders.PointerToRawData);
GCHandle handle = GCHandle.Alloc((magic + ExportTable_rva - delta), GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
// Deallocate pointer
handle.Free();
return theStructure;
}
Please see the attachments for the C++ and C# outputs i am getting....
Attached Images
Last edited by DataMiser; February 25th, 2012 at 08:50 AM .
Reason: added code tags
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width