i know how to write MSIL code but out of curiosity i would like to know if there is a workaround to write assembly code. I can think of a way like writing the code in a string and passing it to a native windows api that executes and returns the result but not sure if this is real or even possible.
i would like to hear your opinions/sugge开发者_StackOverflowstions.Thanks
No it is not possible to write assembly code directly in C# or VB.Net.
The closest you can get to doing this is to separate the assembly code into a native DLL which exported C style function entry points. Then PInvoke into those entry points from the C# / VB.Net application.
Another option is to use C++/CLI as it's possible to inline assembly into a C++/CLI project.
You could assemble it from C#, and pass the generated machine code to a C function like this through P/Invoke.
int execute(char* machine_code)
{
int(*fn)() = machine_code;
return fn();
}
You'd need to worry about making sure that the memory region is executable, but that's beyond the scope of this answer.
You can compile code using fasm.dll, and then use Marshal.GetDelegateForFunctionPointer
to make it callable.
Another (more .NET) option here would be to write it in IL and compile either with ilasm, or something like MonoDevelop which has support for IL projects.
精彩评论