fancycode / MemoryModule

Library to load a DLL from memory.
http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/
Mozilla Public License 2.0
2.74k stars 750 forks source link

Need to use it in C# with and unmanaged dll #99

Open ShayanFiroozi opened 4 years ago

ShayanFiroozi commented 4 years ago

Hi , I need to use this library in C# to load a unmanaged (C++) dll from memory not from file.

is this possible with this library and if it is please tell me how ?

Thank you.

Elmue commented 4 years ago

That is very easy. Compile this project into a DLL and export a function

__declspec(dllexport) BOOL MemoryLoadLibrary(BYTE* data, int size);

In C# you call this with a Byte[] buffer which contains the binary data of the DLL that you want to load to memory:

[DllImport("MemoryModule.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool MemoryLoadLibrary(Byte[] data, int size);
ahdung commented 3 years ago

So how to load MemoryModule.dll from memory?

frankli0324 commented 2 years ago

this is a chicken-egg problem eventually

Elmue commented 2 years ago

It is not a chicken-egg problem. It is a nonsese question.

trungnt2910 commented 2 years ago

So how to load MemoryModule.dll from memory?

Translate it to C#! It's quite easy actually, just more than 1000 lines, and I've got it working on .NET Standard 2.0.

Try this: https://github.com/trungnt2910/MemoryModule.NET I might release a nuget package when I'm less busy, and when I find the cause of this issue.

ahdung commented 2 years ago

@trungnt2910 Great! But I think the nuget package is unpopular, why embed dll, because developers(at least I am) only wants a exe, if we can accept managed dll, why can't accept unmanaged dll, isn't it?

trungnt2910 commented 2 years ago

@ahdung

if we can accept managed dll, why can't accept unmanaged dll, isn't it?

Embedding managed dlls and loading it from memory is much more simple in .NET It's as simple as a Assembly.Load(byte[]) statement, while loading unmanaged dlls are more difficult. Of course, you can always extract them to a temporary location, and then load them from files, but there are a few problems:

But a clean solution is available:

If the process crashes, the OS automatically reclaims all allocated library. No wasted disk space, no file permission headaches!

But I think the nuget package is unpopular

I am neither Microsoft nor James Newton-King, so I don't expect my packages to get popular quickly, but if it solves some problem, I'll maintain it.

ahdung commented 2 years ago

@trungnt2910 You're right, I forgot the Assembly.Load(byte[]) can handle managed thing. I understand the benefits of embeding dll, that's why I'm here. Looking forward to your great work.