Loading mixed mode assembly from unmanaged code - c#

As the title says i want to call a mixed mode assembly from unmanaged code.
To be more precise, i want to load the mixed mode assembly dynamically and then execute some static unmanaged startup code that registers some Managed C++ Wrappers for C# Code.
Is this possible (or do i need to embed the .Net Runtime or use COM?) ?
Has anybody already done this and can share some experience?
PS: If the mixed mode assembly contains a WPF Window will it be started?

You need to get the CLR loaded and initialized. Yes, making a managed class [ComVisible] or hosting the CLR yourself with CorBindToRuntimeEx() is a way to do this. A very simple way is to export a managed function from your DLL, the C++/CLI compiler embeds a thunk in the code that takes care of initializing the CLR. Very easy to do but it does not scale well when the interface to your managed code is fat.
ref class Bootstrap
{
public:
static void Initialize() {
// etc..
}
};
extern "C" __declspec(dllexport)
void __stdcall LoadAndInitialize()
{
Bootstrap::Initialize();
}
You could embellish by passing a function pointer to your native interface. Convert it to a managed delegate with Marshal::GetDelegateForFunctionPointer(). Don't forget to wrap any native declarations with #pragma managed if you do this.

Related

How to ger method of class from a loaded C# dl-library in C++? [duplicate]

How to call managed c# functions from unmanaged c++
Or use a project of mine that allows C# to create unmanaged exports. Those can be consumed as if they were written in a native language.
I used COM interop first, but by now I switched to IJW (it just works), as it is a lot simpler. I have a wrapper C++/CLR DLL (compile with /clr).
A simple example (using statics to make the calls easier):
namespace MyClasses
{
public class MyClass
{
public static void DoSomething()
{
MessageBox.Show("Hello World");
}
}
}
In the DLL I can reference namespaces as follows:
using namespace MyClasses;
And call it:
__declspec(dllexport) void CallManagedCode()
{
MyClass::DoSomething();
}
Now you have an unmanaged DLL export "CallManagedCode" which calls into the managed code.
Of course, you also have to convert data between the managed/unmanaged boundary. Starting with VS2008, Microsoft includes a marshal-helper for converting between unmanaged and managed types. See http://msdn.microsoft.com/en-us/library/bb384865.aspx
I used C++/CLI wrapper classes described here and it was relatively easy to implement.
RE: How to call managed C# code from an unmanaged C++ application?
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.interop/2005-05/msg00030.html
Calling Managed .NET C# COM Objects from Unmanaged C++ Code ...
http://www.codeproject.com/KB/cs/ManagedCOM.aspx
Wrapping a managed C# DLL in a unmanaged C++ project : dll .
http://www.experts-exchange.com/Programming/Languages/.NET/Q_22006727.html

inject C# code to another process and call target functions

I am trying to calling a game functions with code injection. after some try I find a dll that did what I want.
so i saw the dll with ILSpy but cannot understand the code.
class <Module>
{
[SecurityCritical, SuppressUnmanagedCodeSecurity]
[DllImport("", CallingConvention = CallingConvention.ThisCall, SetLastError = true)]
[MethodImpl(MethodImplOptions.Unmanaged)]
internal unsafe static extern float* GetHealth(AttackableUnit*);
}
--------------------------
namespace Native
{
[NativeCppClass]
[StructLayout(LayoutKind.Sequential, Size = 1)]
internal struct AttackableUnit
{
}
}
---------------------
public unsafe float MaxHealth
{
get
{
Native.AttackableUnit* ptr = (Native.AttackableUnit*)base.GetPtr();
if (ptr != null)
{
return *<Module>.Native.AttackableUnit.GetMaxHealth(ptr);
}
return 0f;
}
}
Seems the dll inject c# code to the target app with a c++ dll and bootstrap .net in target.
And now I cannot understand what is the meaning of
[DllImport("", CallingConvention = CallingConvention.ThisCall,
SetLastError = true)]
Why is the file path empty?
How does the dll manage class and function call? I mean what technique the programmer use?
EDIT :
The name of library that I am trying to understand is Elobuddy perhaps helps.
Trying not to kick in a wide-open door, the C# language was not involved in generating this assembly. You are seeing the output of a C++/CLI project. A mixed-mode assembly, it contains both MSIL and native code. You'd generate a similar assembly with File > New > Project > Visual C++ > CLR > Class Library.
The author probably favored it to solve the CLR injection problem. It is not possible to inject a pure managed DLL into another process, the CLR has to first be loaded and initialized before it can execute any managed code. A chicken-and-egg problem that requires reverse-pinvoke (native code calling managed code) the opposite of what [DllImport] does. C++/CLI makes that very easy, I describe the technique in this answer. The Unmanaged Exports utility is popular (google DllExport), an assembly rewriter that uses the same technique that C++/CLI uses.
But the author also wanted to use native C++ code to implement the game hack. He is using a pure native DLL, it contains the GetHealth() function and AttackableUnit class definition. This DLL is implicitly loaded by the OS loader, like DLLs usually are, the reason why an empty string for the [DllImport] attribute is good enough. Otherwise necessary, the compiler cannot know which DLL has this native code, that doesn't get sorted out until the linker runs and uses the import library of the native DLL.
The C++/CLI compiler goes a bit overboard emitting metadata for the pure native constructs in the code. But does its best to make them look as much as possible like their managed equivalents. Do note it is very incomplete, you can't for example see the names of the members of the AttackableUnit C++ class. You will find a lot of other spew in the assembly, a lot of CRT declarations make it into the metadata as well. The native linker does not do a terrific job of hiding it. Mostly because it doesn't have to, this code is pretty well isolated into the internal <Module> class.
Decompiling the machine code for native functions like GetHealth back to the original C++ code is not generally possible. Especially the optimizer built into the back-end of the compiler does a terrific job of making it next to impossible to guess what the original code might have looked like. Hex-Rays is usually mentioned as a machine code decompiler that does a credible job of at least correctly identifying code vs data.

GetProcAddress on managed C# dll

I am trying to load C# dll through LoadLibrary. I am able to load it successfully. Can you please tell me how to use GetProcAddress for this dll so that i can use metods and types defined in this dlls.
Thanks in Advance!!!
EDIT
1 - Best way for this issue is COM. you should set the AssemblyInfo to expose the assembly as COM (ComVisible(true)). See this Microsoft suggestion:
How to call a managed DLL from native Visual C++ code
Unmanaged to Managed calls (C++ to C#)
2 - If you have Windows Vista or higher which has bitlocker, BitLocker can be useful.
3 - But if you cannot using COM, check out this on code-project:
Calling Managed Code from Unmanaged Code
According to this link:
http://social.msdn.microsoft.com/Forums/br/vcmfcatl/thread/cadd6150-de10-47c5-bd5c-a356741c36b3
GetProcAddress will always return NULL for a managed DLL, since it has no exports.
That being said, there are better ways to access managed code from unmanaged code. You should create a C++/CLI wrapper around the unmanaged assembly, and then you can export the managed calls from inside the unmanaged wrapper functions.
Suppose one of your managed functions in class A is
public static void Foo() {}
You might have C++ code:
DLLEXPORT void FooThunk() {
A::Foo();
}
PS: If anybody out there is comfortable with C++/CLI, please edit my answer to include a better example of such a wrapper.

C# code can't "see" the methods in my C++ dll

I have a code written in C++ (that I did not write) and want to use it in C#, so I decided to make a dll and use this class from there.
I have very little knowledge of C++ and am having problems referencing the methods of this class in my C# project.
The C++ code is like this:
#ifndef BeamAn_class
#define BeamAn_class
#define DllExport __declspec( dllexport )
#include <vector>
#include <cmath>
using namespace std;
public class DllExport BeamAn
{
public:
BeamAn();
~BeamAn();
bool SetGeometry(vector<double>); //I didn't put the DllExport here because I already did it for the whole class. It's okay to do this, right?
//other public methods an stuff
private:
//private methods an stuff
}
#endif
In my C# project I added the reference to the C++ dll normally (right click on the project, add reference. The .lib and .h files are in the same folder of the dll).
But looks like Visual Studio can't "see" the methods of my class. I can create a object of the BeamAn type, but can't use any of its methods.
For example, I can do this:
BeamAn contBeam = new BeamAn();
But can't use any of the methods or atributes inside the class, like this: contBeam.SetLoadFactors(1.0,1.2);
Visual Studio says that "BeamAn does not contain a definition for 'SetLoadFactors' and no extension method 'SetLoadFactors' accepting a first argument type 'BeamAn' could be found (are you missing a using directive or an assembly reference?)
Is there more something I should write in the C++ code to make the dll work properly, or am I doing something wrong when referencing it? I know that I'd have to use "DllImport" in my C# code if I was explicit linking, but that's not what I want to do.
Thank you very much!
There are several ways to make C++ library available in C#.
Use PInvoke - directly call your C++ code. See this article for more information. Also see pinvoke.net for general reference.
Use an interop language to create a managed wrapper around your unmanaged code. If you're in the Microsoft world I would recommend C++/CLI to create mixed mode libraries (dlls that contain both managed and unmanaged code). Here is a brief (and old) article introducing C++/CLI.
Make your C++ COM accessible. Since the code isn't yours this one might not be useful to you. See this post for more information about C++ and COM.
For simple scenarios PInvoke is probably the easiest. For more complicated interactions of the managed and unmanaged code I would recommend writing a mixed mode dll with an interop language. And if those don't work for you, use COM.
To address the error you receive: you can't add a reference to a C++ library from a C# project - they are completely different languages with different memory management systems, different type systems, different everything (well, a lot of things). Also, you can't pass data structures (like vectors, maps or sets) from unmanaged code to managed code.
to use c++ code in a c# project, you have 2 options:
wrap your c++ class in a managed c++ class
use a library called swig
a link that might interest you: Wrapping Visual C++ in C#

Calling C# from C++, Reverse P/Invoke, Mixed Mode DLLs and C++/CLI

As I understand it I can use reverse P/Invoke to call C# from C++. Reverse P/Invoke is simply a case of:
Create you managed (c#) class.
Create a c++/cli (formerly managed c++) class library project. Use this to call the managed c# class (presumably via a reference).
Call the c++/cli code from native c++.
Questions:
Is this correct?
Is the DLL created at step 2 known as a mixed mode DLL?
Has C++/CLI completely superseded Managed C++ as far as MS are concerned?
Is COM completely avoided using this approach?
At what point would the CLR be created and run, and by whom?
Thanks in advance
Here are the answers to the best of my knowledge:
Yes
Yes, it is a mixed mode DLL (In fact, you can make one file of your native C++ project managed and create this C++/CLI class in that file and call the code directly from that file. You don't even need a separate DLL to accomplish this.
C++/CLI and Managed C++ both represent same thing. The only difference is that in the older version till Visual Studio 2003, it was termed as Managed C++. Later on, the syntax was changed quite a lot and it was renamed as C++/CLI. Have a look at this link for details.
Yes
CLR will be used whenever a call to the managed DLL is made.
Note, you can also do a IL roundtrip of the C# dll and export static methods, which work basically the same as the exports in C++/CLI. However, this is always a post-compile step, and it does have some caveats (which your C++/CLI export have too, btw.).
You can ILDASM both the C# and the C++/CLI DLLs to see how exports are don; it is something like this (from a sample on the net):
// unmexports.il
// Compile with : ilasm unmexports.il /dll
assembly extern mscorlib {}
..assembly UnmExports {}
..module UnmExports.dll
// This flag is important
..corflags 0x00000002
// This instructs the CLR to create a marshaling thunk for the unmanaged caller
..vtfixup [1] int32 fromunmanaged at VT_01
..data VT_01 = int32(0)
..method public static void foo()
{
..vtentry 1:1
..export [1] as foo
ldstr "Hello from managed world"
call void [mscorlib]System.Console::WriteLine(string)
ret
}
With ilasm 2.0 you need less code because it can generate most of the gunk by itself. Only the .export directive is really needed now.
// unmexports.il
// Compile with : ilasm unmexports.il /dll
.assembly extern mscorlib { auto }
.assembly UnmExports {}
.module UnmExports.dll
.method public static void foo()
{
.export [1] as foo
ldstr "Hello from managed world"
call void [mscorlib]System.Console::WriteLine(string)
ret
}

Categories

Resources