4

Hold it right there! You may think this has already been asked millions of time and has been answered as many time as the Earth has spun around the Sun, but please bear with me on this one.

My task is simple: In my C++ (Windows) program, I want to be able to execute some managed (C# or VB.NET etc) codes.

Wait! Before you CTRL-T, go grab a random link from Google and slap it in my face, and say "Learn to search!", please continue reading:

I started from here http://sites.google.com/site/robertgiesecke/ which allowed me to export C# functions as C style functions, and then use it in C++. It works all right. But now I have two binaries, the native exe and the managed dll.

How can I embed the dll into the exe and map it into the memory, and finally call it from there? In other words, I want to have only one single exe containing both the native exe and the managed dll.

Of course I have already tried this http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/
Unfortunately that doesn't work, the code fails to finish the "attach" process at the end. I'm guessing it's because of the dll's managed form.

Thanks for reading.

EDIT: I really don't want to use C++/CLI by all means :(

user25101622
  • 193
  • 2
  • 13
  • 3
    You'll have to host the CLR yourself so you can provide your own IHostAssemblyManager and IHostAssemblyStore implementations. Makes the Giesecke hack unnecessary as well. – Hans Passant Feb 12 '12 at 10:15
  • That totally nailed the problem :D Post it as answer, and I'll mark it. – user25101622 Feb 12 '12 at 11:42

2 Answers2

0

What you're trying to create is a "Mixed mode" assembly. This can only be created if you create a "Managed-C++" Assembly/Executable in Visual Studio.

From my years of experience, C#/VB.NET doesn't support this. Though I could be wrong and it might just be a limitation of Visual Studio and not C# per-se.

akhisp
  • 675
  • 3
  • 5
0

What you're trying here is something not really supported due to security concerns. Essentially you're trying to execute your own data blocks (which might even be marked with the nx (no execute) flag. I tried something similar in the past (for DRM reasons; only as in "avoid decompilers" - I'm no fan of restrictive DRM). It is possible, but it is a PITA to use and error prone depending on the security settings of the target machine. If possible avoid it at all costs.

The code on the blog is essentially using the right approach, however that code will work with unmanaged libraries only (as you noticed already). That's simply due to the way managed libraries and executables are built (there's essentially just a small native stub for executables to start the runtime environment; but there's none for libraries (and therefore no native entry point; which would be required for that approach)).

Mario
  • 35,726
  • 5
  • 62
  • 78