Rob The Quant
Rob The Quant

Reputation: 397

Is there a way to dynamically generate native x86 code and execute it from .NET?

I'd like to dynamically generate native unmanaged x86 code and then execute it super fast from managed .NET. I know I could emit some IL code and execute that, but I'm thinking the jetting would take too much time to get the benefit of any speed gain I get from it.

I need super fast code, I want to generate a function with the x86 opcodes in memory and pass a fixed pointer to a memory block to it, so it would make some really fast calculations on that block.

I just not sure how to call the native code from .net. remember this should be on the fly in memory, not building a dll. Speed is what really matters here. It's part of a genetic computation project.

Upvotes: 2

Views: 530

Answers (2)

Mark Benningfield
Mark Benningfield

Reputation: 2892

The short answer is that you can't do that with C#.

You can do that with C++/CLI, by building a mixed-mode assembly that does your "super fast" calculations in native code. That way, you wouldn't need (presumably) to generate executable code "on-the-fly".

If for some reason you can't hard-code the calculation functions, then you will have to acquire executable memory from the operating system.

On Windows, you do that with the VirtualAlloc and VirtualProtect functions. Again, doing that from C# would require P/Invoke interop, which would most likely reverse your speed gains.

Upvotes: 1

TekOps
TekOps

Reputation: 186

The C language is the "portable assembler" and you can generate x86 opcodes directly (writing in assembler would be better). If you compiled the C code into an object, you could link it into .net as a library.

If you are trying to generate executable code dynamically (on-the-fly) you would need to allocate a binary array, push the object code into the array, then get the beginning address of the array after the memory headed and assign that to a function pointer and call it.

However, antivirus software specifically looks for this behavior and would identify your code a virus more than likely.

Also your processor is designed to have "code" memory segments and "data" memory segments. Typically you cannot dynamically modify the code segment without causing a segfault and you cannot execute out of a data segment without causing a segfault.

Also, you code would only run on a SISC processor (x86) and not on a RISC processor.

There is a lot to consider.

We used to do this in assembler in the old days on SISC systems.

Cheers, David

Upvotes: 1

Related Questions