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....

Recommended Answers

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

Jump to Post

All 2 Replies

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.