>>20
Is it a DLL or an EXE? The difference is mostly in how it's build, especially the flags and presence of relocations.
If it's a DLL, you can always load it manually. You can do the same for EXE, but depending on the presence of relocations or not, you'll need to take different paths.
As I said in my post, the actual details are rather involved and require you to understand the PE loader well, but it's not too difficult, it goes like this (much simplified version):
1. Read/parse the header.
2. Map the header and sections into memory, set proper protection options for the pages.
VirtualAlloc and
VirtualProtect will need to be used at minimum.
3. Resolve imports, either directly or using your own code.
LoadLibraryA/W,
GetModuleHandleA/W and
GetProcAddress may need to be used, but it's not absolutely needed.
4. Apply relocations if present.
5. Execute tls-callbacks and other initialization code.
6. Call the DLL's entrypoint.
This is how
LoadLibrary works at minimum, if you were to do your own
LoadLibrary like that, you may as well write your own
GetProcAddress (just look up the imports in the export table, can only be done by accessing memory). If you want to register the DLL so it can be detected by other tools, you'll need to learn a bit about
PEB->Ldr->InMemoryOrderModuleList, same goes about finding other DLLs (
GetModuleHandle).
The gist of it is that you can pretty much load any code in memory by merely having a memory allocator (and usually also a way to change the page protections, so
VirtualAlloc and
VirtualProtect) and a proper understanding of the PE file format and how the loader works.
That is if your code is a DLL and has relocations. If not? You can always just create a dummy process, remotely dealloc all memory, and reconstruct the executable like the PE loader would do (remotely), then adjust the context (or just create a remote thread), and you would have generated a process without it having a file on disk. I'm really not going to explain this in detail, and you should go read up the documentation yourself, it's too long and you should do your homework.
If you are lazy and have no interest in doing your homework, just use one of the PE packers/protectors that support bundling DLLs - there are quite a few.