Hi All,

I am trying to convert the following C++ code to C#.

pExportDir = (PIMAGE_EXPORT_DIRECTORY)GetPtrFromRVA(exportsStartRVA, pNTHeader, pImageBase);

template <class T> LPVOID GetPtrFromRVA( DWORD rva, T* pNTHeader, PBYTE imageBase ) // 'T' = PIMAGE_NT_HEADERS 
	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);

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
        return theStructure;


Please see the attachments for the C++ and C# outputs i am getting....

Attachments C#.png 27.7 KB C++.png 25.73 KB

What "includes" are you using for the C# code?

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

This article has been dead for over six months. Start a new discussion instead.