6

I trying to call .NET function from native code and via virtual address. I wrote a simple class library that have a class and static method and I browse with dnSpy

I also checked ImageBase value is 0x10000000

using System;

// Token: 0x02000002 RID: 2
public class Class1 : object
{
    // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250
    public static int Calculate(int x, int y)
    {
        return x + y;
    }
}

I'm looking at the documentation of LoadLibrary which says:

Loads the specified module into the address space of the calling process.

When I call calculate function, I'm getting AV Error.

Exception thrown at 0x10002050 in ConsoleApplication1.exe: 0xC0000005: Access violation executing location 0x10002050. occurred

#include <Windows.h>
#include <iostream>

using namespace std;

typedef int(*Calculate)(int x, int y);

PVOID RvaToVa(PVOID rva, PVOID imageBase)
{
    return PVOID((int)rva + (int)imageBase);
}

int main()
{
    HMODULE hModule = LoadLibrary(L"ClassLibrary1.dll");
    if (!hModule)
    {
        cout << GetLastError() << endl;
        return 0;
    }

    PVOID fPtr = RvaToVa((PVOID)0x00002050, (PVOID)0x10000000);
    Calculate calculate = (Calculate)fPtr;

    if (calculate)
    {
        int result = calculate(31, 32);
        cout << result << endl;
    }
    FreeLibrary(hModule);
    return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
İsmail Kocacan
  • 1,204
  • 13
  • 38
  • 6
    You can't do that. You need to load & initialize the CLR. – SLaks Nov 29 '17 at 20:08
  • 5
    An Assembly (compiled C# library into `.dll` file) is not native code, is compiled into an intermediate language. You cannot execute it without the runtime (CLR). – Federico Dipuma Nov 29 '17 at 20:11
  • 1
    Clever attempt, but I agree with the previous comments. Impossible, unless you are targeting a normal WINAPI, STDCALL or CDECL DLL (AND its dependency DLLs are available), not a DLL that requires a runtime Engine – Grantly Nov 29 '17 at 20:29
  • You can use the unmanaged export library to do that or export the class as an ActiveX component. Have a look here: https://stackoverflow.com/q/4818850/2557263 – Alejandro Jan 10 '18 at 12:32
  • Thanks @Alejandro I know unmanaged export library. – İsmail Kocacan Jan 12 '18 at 19:07

0 Answers0