473,408 Members | 2,477 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

MSIL and C#

Hi all,

I'm just starting to experiment with MSIL but am getting confused
about c# and MSIL integration.

I understand that c# is compiled into MSIL before it is JIT'ed and
then executed. I also understand that it is possible for me to
generate my own MSIL using the System.Reflection.Emit namespace.
However, is it possible for my c# code to call into my
pre-MSIL-compiled code, passing and returning values?

I dont see why this shouldn't be possible, but I can't seem to find
any examples out there. Know of any?

Many thanks
Rick
Jul 21 '05 #1
6 2923

"TrickyDicky" <ri***@smarthumanlogistics.com> wrote in message
news:94*************************@posting.google.co m...
Hi all,

I'm just starting to experiment with MSIL but am getting confused
about c# and MSIL integration.

I understand that c# is compiled into MSIL before it is JIT'ed and
then executed. I also understand that it is possible for me to
generate my own MSIL using the System.Reflection.Emit namespace.
However, is it possible for my c# code to call into my
pre-MSIL-compiled code, passing and returning values?


To clarify my understanding, do you mean calling into MSIL code you
generated?

If so, you would basically just generate an assembly with
System.Reflection.Emit and save it to disk, loading it in your application.
Jul 21 '05 #2
Hi Daniel,

Yep, I want to call into MSIL code that I had previously generated.

I thought this would be possible.

So it it just as simple as adding an assembly reference to my existing
c# solution, then calling into the pre-compiled functions?

Or I suppose if I didn't know which pre-compiled assemblies were
avaialble, I'd just have to late bind to them and have a common
interface?

Ta
r

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 21 '05 #3

"Rick Livesey" <ri***@smarthumanlogistics.com> wrote in message
news:%2***************@TK2MSFTNGP11.phx.gbl...
Hi Daniel,

Yep, I want to call into MSIL code that I had previously generated.

I thought this would be possible.

So it it just as simple as adding an assembly reference to my existing
c# solution, then calling into the pre-compiled functions?

Or I suppose if I didn't know which pre-compiled assemblies were
avaialble, I'd just have to late bind to them and have a common
interface?


Yeap, thats precisely what you would do.
Jul 21 '05 #4
Rick Livesey <ri***@smarthumanlogistics.com> wrote:
Hi Daniel,

Yep, I want to call into MSIL code that I had previously generated.

I thought this would be possible.

So it it just as simple as adding an assembly reference to my existing
c# solution, then calling into the pre-compiled functions?

Or I suppose if I didn't know which pre-compiled assemblies were
avaialble, I'd just have to late bind to them and have a common
interface?

Ta
r

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!


What follows is a simple example from:

Programming C#, Third Edition
by Jesse Liberty
http://www.amazon.com/exec/obidos/asin/0596004893
http://www.oreilly.com/catalog/progcsharp3/

Chapter 18: Attributes and Reflection
p.534

Look for "public class ReflectionTest"

//-----[BEGIN]----
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;

namespace Programming_CSharp {

public class TestDriver {

public static void Main(string[] args) {

const int val = 2000; // 1..2000
// 1,000,000 iterations
const int iterations = 1000000;
int result = 0;

// run the Benchmark
MyMath m = new MyMath();
DateTime startTime = DateTime.Now;
for( int i = 0; i < iterations; ++i )
result = m.DoSumLooping( val );

TimeSpan elapsed = DateTime.Now - startTime;
Console.WriteLine( "Sum of ({0}) = {1}", val,
result );
Console.WriteLine( "Looping. Elapsed
milliseconds is: "
+ elapsed.TotalMilliseconds.ToString()
+ " for {0} iterations" , iterations
);

ReflectionTest t = new ReflectionTest();

startTime = DateTime.Now;
for( int i = 0; i < iterations; ++i )
result = t.DoSum(val);

elapsed = DateTime.Now - startTime;
Console.WriteLine( "Loop: Sum of ({0}) = {1}",
val, result );
Console.WriteLine( "Looping. Elapsed
milliseconds is: "
+ elapsed.TotalMilliseconds.ToString()
+ " for {0} iterations" , iterations
);

} // end method Main
}

public class MyMath{
// sum numbers with a loop
public int DoSumLooping(int initialVal) {
int result = 0;
for( int i = 1; i <= initialVal; ++i )
result += i;

return result;
} // end method DoSum

} // end class MyMath

public interface IComputer {
int ComputeSum();
}

// responsible for creating the BruteForceSums
// class and compiling it and invoking the
// DoSums method dynamically
public class ReflectionTest {
IComputer theComputer = null;

// the private method which emits the assembly
// using op codes
private Assembly EmitAssembly(int theValue ){
// Create an assembly name
AssemblyName assemblyName =
new AssemblyName();
assemblyName.Name = "DoSumAssembly";

// Create a new assembly with one module
AssemblyBuilder newAssembly =
Thread.GetDomain().DefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run
);
ModuleBuilder newModule =
newAssembly.DefineDynamicModule("Sum");

// Define a public class named "BruteForceSums"
// in the assembly
TypeBuilder myType =
newModule.DefineType(
"BruteForceSums",
TypeAttributes.Public
);

// Mark the class as implementing IComputer
myType.AddInterfaceImplementation(
typeof(IComputer)
);

// Define a method on the type of call. Pass an
// array the defines the types of the parameters
// the type of the return type, the name of the
// method, and the method attributes.
Type[] paramTypes = new Type[0];
Type returnType = typeof(int);
MethodBuilder simpleMethod =
myType.DefineMethod(
"ComputeSum",
MethodAttributes.Public |
MethodAttributes.Virtual,
returnType,
paramTypes
);

// Get an ILGenerator. This is used
// to emit the IL that you want.
ILGenerator generator =
simpleMethod.GetILGenerator();

// Emit the IL that you'd get if you
// compiled the code example
// and then run ILDasm on the output.

// Push zero onto the stack. For each 'i'
// less than 'theValue',
// push 'i' onto the stack as a constant
// add the two values at the top of the stack.
// The sum is left on the stack
generator.Emit( OpCodes.Ldc_I4, 0 );
for( int i = 1; i <= theValue; ++i ){
generator.Emit( OpCodes.Ldc_I4, i );
generator.Emit( OpCodes.Add );
}
// return the value
generator.Emit( OpCodes.Ret );

// Encapsulate information about the method and
// provide access to the method's metadata
MethodInfo computeSumInfo =
typeof( IComputer ).GetMethod("ComputeSum");

// Specify the method implementation
// Pass in the MethodBuilder that was returned
// by calling DefineMethod and the methodInfo
// just created.
myType.DefineMethodOverride( simpleMethod,
computeSumInfo );

// Create the type.
myType.CreateType();
return newAssembly;

} // end method EmitAssembly

// the public method called by the driver
public int DoSum(int theValue){
// if you don't have a reference
// to the dynamically created class
// create it
if( theComputer == null ){
GenerateCode(theValue);
}
return (theComputer.ComputeSum());
} // end method DoSum

private void GenerateCode(int theValue ){
Assembly theAssembly = EmitAssembly( theValue );
theComputer =
(IComputer)theAssembly.CreateInstance("BruteForceS ums");
} // end method GenerateCode

} // end class ReflectionTest
}
//-----[END]----
Jul 21 '05 #5
Thanks Guys,

One more question. Here's the setup:

I have a C# environment that holds basic global utilities into which I
want to be able to load the late-bound MSIL Assembly (probably using
Assembly.Load), therefore giving it access to the utilities.

Am I right in thinking there are 2 ways to do this:

1) Pass instances of the utilities in to the MSIL assembly on creation.

2) Make each MSIL Assembly reference the external c# utilities
namespace, therefore giving it access to a set of global utilities.

Ideally this utilities set should be the same instance for every MSIL
Assembly, (it may contain cached data).

Hope this makes sense. Any tips would be appreciated.
Thanks
Rick

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 21 '05 #6
Thanks Guys,

One more question. Here's the setup:

I have a C# environment that holds basic global utilities into which I
want to be able to load the late-bound MSIL Assembly (probably using
Assembly.Load), therefore giving it access to the utilities.

Am I right in thinking there are 2 ways to do this:

1) Pass instances of the utilities in to the MSIL assembly on creation.

2) Make each MSIL Assembly reference the external c# utilities
namespace, therefore giving it access to a set of global utilities.

Ideally this utilities set should be the same instance for every MSIL
Assembly, (it may contain cached data).

Hope this makes sense. Any tips would be appreciated.
Thanks
Rick

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Raymond Lewallen | last post by:
Is there some article out there that helps in reading MSIL? I've been looking but can't find anything, and I'm probably just looking in the wrong spots for the wrong keywords. I understand mov,...
7
by: Raymond Lewallen | last post by:
Microsoft, Can I make a request for a newsgroup specific to MSIL? I have taken great interest in MSIL and have done a lot of reading into MSIL, and written, compiled and tested with success a...
6
by: Pawel | last post by:
Ary you know tools to convert MSIL code (Assembly) to Win32 (not Just In Time)?
7
by: carl.manaster | last post by:
Hi, I'd like to take a string containing MSIL code, assemble it, execute it, and receive the result all from my running C# application. So far I've managed to manually create some MSIL code...
4
by: James dean | last post by:
My understanding is the MSIL runs on the CLR and the CLR is basically the JIT compiler plus Garbage collection. This part "MSIL runs on the CLR" is a bit vague to me can anyone give me a clearer...
3
by: NigelW | last post by:
Clarification needed please. If I compile a C++ program with the /clr option inpsection of the resulting assembly with ILDASM shows MSIL even for methods in classes for which I have not...
1
by: John Doe | last post by:
Hi all, I have a lot of confusion about what this runtime environment is. When I write an application with unmanaged code and unmanaged data, can I compile it to the MSIL, or it will compile...
3
by: Mark Fox | last post by:
Hello, I have read a lot about how the .NET Framework uses MSIL as its intermediate language. If I have a project in C# in VS.NET 2003, how do I get the MSIL for it so I could look at it? ...
3
by: TrickyDicky | last post by:
Hi all, I'm just starting to experiment with MSIL but am getting confused about c# and MSIL integration. I understand that c# is compiled into MSIL before it is JIT'ed and then executed. I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.