C# function pointer? - c#

I'm having a problem with C#, I'd like to get a pointer of a method in my code, but it seems impossible. I need the pointer of the method because I want to no-op it using WriteProcessMemory. How would I get the pointer?
Example code
main()
{
function1();
function2();
}
function1()
{
//get function2 pointer
//use WPM to nop it (I know how, this is not the problem)
}
function2()
{
Writeline("bla"); //this will never happen because I added a no-op.
}

I know this is very old, but an example of something like a function pointer in C# would be like this:
class Temp
{
public void DoSomething() {}
public void DoSomethingElse() {}
public void DoSomethingWithAString(string myString) {}
public bool GetANewCat(string name) { return true; }
}
...and then in your main or wherever:
var temp = new Temp();
Action myPointer = null, myPointer2 = null;
myPointer = temp.DoSomething;
myPointer2 = temp.DoSomethingElse;
Then to call the original function,
myPointer();
myPointer2();
If you have arguments to your methods, then it's as simple as adding generic arguments to your Action:
Action<string> doItWithAString = null;
doItWithAString = temp.DoSomethingWithAString;
doItWithAString("help me");
Or if you need to return a value:
Func<string, bool> getACat = null;
getACat = temp.GetANewCat;
var gotIt = getACat("help me");

EDIT: I misread your question and didn't see the bit about wanting to NOP a statement with doing raw memory manipulation. I'm afraid this isn't recommended because, as Raymond Chen says, the GC moves stuff around in memory (hence the 'pinned' keyword in C#). You probably can do it with reflection, but your question suggests you don't have a strong grasp of the CLR. Anyway, back to my original irrelevant answer (where I thought you just wanted information on how to use delegates):
C# isn't a scripting language ;)
Anyway, C# (and the CLR) has "function pointers" - except they're called "delegates" and are strongly typed, which means you need to define the function's signature in addition to the function you want to call.
In your case, you'd have something like this:
public static void Main(String[] args) {
Function1();
}
// This is the "type" of the function pointer, known as a "delegate" in .NET.
// An instance of this delegate can point to any function that has the same signature (in this case, any function/method that returns void and accepts a single String argument).
public delegate void FooBarDelegate(String x);
public static void Function1() {
// Create a delegate to Function2
FooBarDelegate functionPointer = new FooBarDelegate( Function2 );
// call it
functionPointer("bla");
}
public static void Function2(String x) {
Console.WriteLine(x);
}

public string myFunction(string name)
{
return "Hello " + name;
}
public string functionPointerExample(Func<string,string> myFunction)
{
return myFunction("Theron");
}
Func functionName.. use this to pass methods around. Makes no sense in this context but thats basically how you would use it

I'd wish it is useful
class Program
{
static void Main(string[] args)
{
TestPointer test = new TestPointer();
test.function1();
}
}
class TestPointer
{
private delegate void fPointer(); // point to every functions that it has void as return value and with no input parameter
public void function1()
{
fPointer point = new fPointer(function2);
point();
}
private void function2()
{
Console.WriteLine("Bla");
}
}

Actually there are real function pointers introduced in C# 9
Official Documentation
From the link:
You can define a function pointer using the delegate* syntax. The compiler will call the function using the calli instruction rather than instantiating a delegate object and calling Invoke
Example for the example in the post:
static unsafe void function1()
{
//get function2 pointer
delegate*<void> ptr = &function2;
// do something with ptr
}

Rewriting a method cannot be done directly from managed code, however the unmanaged .net profiling api can be used to do this. See this msdn article for example on how to use it.

Related

Using a Local Function over an Action as an input param

I have a method that is taking in an Action<string> (see simple example below), but in the calling method where the Action is constructed, Resharper is suggesting that a Local Function should be used.
What are the recommended practices around using Local Functions in place of Actions, does it matter, or are there gotchas to be aware of?
public void Caller()
{
string holder;
Action<string> act = s => holder = s;
void SetHolder(string s) => holder = s;
DoStuff(act);
DoStuff(SetHolder);
}
public void DoStuff(Action<string> setHolder)
{
setHolder("holders new string");
}
Taking you code and putting it through sharplab.io, we can see that the code gets lowered to:
public class Class
{
[CompilerGenerated]
private sealed class <>c__DisplayClass0_0
{
public string holder;
internal void <Caller>b__0(string s)
{
this.holder = s;
}
internal void <Caller>g__SetHolder1(string s)
{
this.holder = s;
}
}
public void Caller()
{
Class.<>c__DisplayClass0_0 #object = new Class.<>c__DisplayClass0_0();
Action<string> setHolder = new Action<string>(#object.<Caller>b__0);
this.DoStuff(setHolder);
this.DoStuff(new Action<string>(#object.<Caller>g__SetHolder1));
}
public void DoStuff(Action<string> setHolder)
{
setHolder("holders new string");
}
}
Because both act and SetHolder are closures over holder, when Caller is invoked a new closure class instance is created and new Action delegates are created for both the lambda and the local function. So the resultant code is identical for both.
Therefore, given the way you are using them here, it just comes down to readability (as many R# recommendations do). Local functions arguably have better syntax, so R# recommends you use it that way.
One of the benefits of local functions over delegates are that invoking them does not incur in a delegate instantiation and delegate invocation which is lost in your example because you are wrapping it with a delegate to pass it to DoStuff.
Have a look at the documentation to know all about local functions.

C# Input system - Since '{method}' returns void, a return keyword must not be followed by an object expression

Trying a shot to a little advanced text adventure here, I have an inventory class. (isn't an error) and it all works great!
I'm trying to implement a feature of an input. That it just leads to input, and then returns the arguments back to that class. I thought it would be easy. Turned out a 'void' method can't return something. I don't know what I should use then.
I searched a bit on Google but can't find google, and the answers on here are all XML or more experienced programmers. There are also a few simpler once, but those are unanswered.
This is my Program class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inventory_system_test
{
class Program
{
//Objects
static private Inventory inv = new Inventory();
//strings
static private string args;
//variables
static void Main(string[] args)
{
Write("Do you want to kill dave?");
input();
}
static public void input()
{
bool done = false;
Writen("Enter a command: ");
args = Console.ReadLine();
while (!done)
{
if (args.Contains("add inv "))
{
args = args.Split()[2];
inv.additem(args);
}
else if (args.Contains("remove inv "))
{
args = args.Split()[2];
inv.removeitem(args);
}
else if (args.Contains("see inv"))
{
Write("INVENTORY:");
inv.getinv();
}
else if (args == "close")
{
Environment.Exit(0);
}
else
{
done = true;
return args; ///**Here is the error ofcourse.**
}
}
} //Input files things :)
#region Easy Commands (Write, Sleep)
//Write to console
public static void Write(string writev)
{
Console.WriteLine(writev);
}
//Sleep for 'int sleeptime' in milliseconds
public static void Sleep(int sleeptime)
{
System.Threading.Thread.Sleep(sleeptime);
}
public static void Writen(string writen)
{
Console.Write(writen);
}
#endregion
}
}
I'm getting to understand scripting more and more, and that's just by asking question and searching Googles, I really love the people on Stackoverflow! Thank you all for your help!
So uh.. how would I go and do this?
There aren't many methods.. And I wouldn't know what to do from here.
Turned out a 'void' method can't return something. I don't know what I should use then.
You should use a method which is declared to return the kind of information you want to return! When a method is void, that specifically means it's not meant to return anything.
In this case it looks like you're trying to return the value of args, which is a string variable, so you want:
public static string input()
Additionally:
You should follow .NET naming conventions
There's no reason for your args variable to be static - it would better as a local variable within your method
args is an odd name for this variable anyway, in my view. Given that you're asking for a command, why not use command as the variable name?
I suggest you read the MSDN page on methods or look in a good book about C# to learn more about return types, parameters and so on.
From void (C# Reference)‎
When used as the return type for a method, void specifies that the
method does not return a value.
But your input method returns a value so..
Console.ReadLine() methods retursn a string so your args is looks like a string. That's why you should change your return type as a string like;
public static string input()
{
}
You declare args as being of type string, so that's what you should return:
static public string input()
{
...
return args;
}

Call a method in class from an external dll

so I'm looking for a way to call a method in an application externally from a dll. (see example below) This is what I'm trying however it's a) not working and b) if it was working i have a feeling that calling DynamicInvoke is going to be painfully slow.
first all if I did want to do it this way how do I deal with returns types as currently this will errors saying callthisexternally() has wrong return type.
is there a better way to do this?
--- within a a dll ---
public class mydll
{
// etc.. blah blah
public object callfromdll(string commandName, int requiredArgs, Delegate method)
{
// do stuff
// now invoke the method
return method.DynamicInvoke(method.Method.GetParameters().Select(p => p.ParameterType).ToArray());
}
}
-- within an application that's refrancing the above dll --
public someclass
{
// etc.. stuff here
mydll m = new mydll();
m.callfromdll("callthisexternally", 0, new Action(callthisexternally));
// the function to be called externally
public string callthisexternally()
{
// do stuff
return "i was called!";
}
}
Without more details of what callFromDll is supposed to do you can do this simply with a Func Delegate
public class mydll
{
// etc.. blah blah
public T callfromdll<T>(string commandName, int requiredArgs, Func<T> method)
{
// do stuff
// now invoke the method
return method();
}
}
If your do stuff was doing something to generate a int you just need to use the correct method siginature.
public class mydll
{
// etc.. blah blah
public T callfromdll<T>(string commandName, int requiredArgs, Func<int, T> method)
{
int x = SomeComplexFunction(commandName, requiredArgs);
return method(x);
}
}
-- within an application that's refrancing the above dll --
public someclass
{
public void test()
{
// etc.. stuff here
mydll m = new mydll();
var result = m.callfromdll("callthisexternally", 0, new Func(callthisexternally));
//result contains "i was called, and my result was #" and where # is replace with the number passed in to callthisexternally
}
// the function to be called externally
public string callthisexternally(int x)
{
// do stuff
return "i was called, and my result was " + x;
}
}
Now your DLL will pass in the value it calculated for x in to the function you passed in and it will give you the result from that function.
I'd just like to add that using DynamicInvoke is, as you suspected, very slow and should be avoided if possible:
What is the difference between calling a delegate directly, using DynamicInvoke, and using DynamicInvokeImpl?
Not exactly sure what your trying to do here, maybe your new to C# so.
Do you try to reference a dll that you didnt wrote?, its ok just add a reference to the dll in your project. If written also in c# it usually works.
Remind that there are tons of dll's as part of SDK's that can be included that way to suit your project. Here a video to explain it https://www.youtube.com/watch?v=gmz_K9iLGU8
If you like to execute another program externally
using System.Diagnostics;
class Program
{
static void Main()
{
// Use Process.Start here.
Process.Start("C:\\HitchHickersGuide.exe /Towl /42");
}
}

Passing code as parameter C#

I'm trying to pass a reference to a function as a parameter
It's hard to explain
I'll write some example pseudo code
(calling function)
function(hello());
function(pass)
{
if this = 0 then pass
else
}
hello()
{
do something here
}
Sorry if it does not make much sense
But I'm trying to reduce used code and I thought this would be a good idea.
How can I do this in C#?
You can pass code to a method by using delegates, for example, the Action delegate:
void MyFunction(Action action)
{
if (something == 0)
{
action();
}
}
void Hello()
{
// do something here
}
Usage:
MyFunction(Hello);
I'm trying to pass a reference to a function as a parameter
It's hard to explain
It may be hard to explain, but it is very easy to implement: the code below calls MyFunction passing it a parameterized piece of code as a parameter.
static void MyFunction(Action<string> doSomething) {
doSomething("world");
}
static void Main(string[] args) {
MyFunction((name) => {
Console.WriteLine("Hello, {0}!", name);
});
}
You can use delegate types provided by the system (Action and Func) or write your own.
Here is an example:
using System;
public class Example
{
public void Method1(Action hello)
{
// Call passed action.
hello();
}
public void Method2()
{
// Do something here
}
public void Method3()
{
Method1(Method2);
}
}

C#: Creating an instance of an abstract class without defining new class

I know it can be done in Java, as I have used this technique quite extensively in the past. An example in Java would be shown below. (Additional question. What is this technique called? It's hard to find an example of this without a name.)
public abstract class Example {
public abstract void doStuff();
}
public class StartHere{
public static void main(string[] args){
Example x = new Example(){
public void doStuff(){
System.out.println("Did stuff");
}
};
x.doStuff();
}
}
Now, my main question would be, can this also be done in C#, and if so, how?
The Java technique is called "Anonymous inner class", and there is no equivalent in C#.
With lamba expressions and class initializers you can get the same behaviour with a bit of effort.
public class Example {
public Action DoStuff;
public Action<int> DoStuffWithParameter;
public Func<int> DoStuffWithReturnValue;
}
class Program {
static void Main(string[] args) {
var x = new Example() {
DoStuff = () => {
Console.WriteLine("Did Stuff");
},
DoStuffWithParameter = (p) => {
Console.WriteLine("Did Stuff with parameter " + p);
},
DoStuffWithReturnValue = () => { return 99; }
};
x.DoStuff();
x.DoStuffWithParameter(10);
int value = x.DoStuffWithReturnValue();
Console.WriteLine("Return value " + value);
Console.ReadLine();
}
}
One problem with this solution that I just realized is that if you were to create fields in the Example class, the lambda expressions would not be able to access those fields.
However, there is no reason that you could not pass the instance of Example to the lambda expressions which would give them access to any public state that example might hold. AFAIK that would be functionally equivalent to the Java Anonymous Inner Class.
P.S. If you are going to vote an answer down, do us all a favour and add a comment as to why you disagree :-)
Typically, problems that are solved with anonymous inner classes in Java are solved in a much cleaner fashion using delegates in .Net. Your example is a little too simplistic to determine your intent. If your intent by using the abstract class is to pass around a "behavior" think about just using an Action delegate instead.
public class StartHere{
public static void main(string[] args){
Action doStuff = () => Console.WriteLine("Did stuff");
executeSomething(doStuff);
}
public static void executeSomething(Action action)
{
action();
}
}
That can't be done in C#; you need to declare a new class type. The closest you can get in C# is probably a named nested class:
public class StartHere{
private class Foo : Example {
public override void doStuff()
{
Console.WriteLine("did stuff");
}
}
public static void Main(string[] args){
Example x = new Foo();
x.doStuff();
}
}
This is not supported in C#, and if it were up to me it shouldn't be so either.
The proliferation of inner classes in java is mainly due to the lack of delegates or lambdas, which C# has. So while this type of functionality currently is "your only hope" in java, you can usually use other mechanisms in C# to achieve the same ends. Java feels like playing the piano with one hand in this regard.
(Admittedly a lot of us have gotten quite good at this one-handed playing; and now it seems like we have to wait at least until java 8 for closures...)
Since your class represents only an action, you can use a delegate in your case, there is an existing delegate :
public delegate void Action();
This is the exact equivalent of your class.
And the déclaration of your anonymous class is even cleaner :
Action action = () => Console.WriteLine("Hello world");
action(); // invoke
you can even use closure :
public void Hello(string name)
{
Action action = () => Console.WriteLine("Hello " + name);
action(); // will call the above lambda !
}
While all good answers, most of the work arounds suggested rely on C# 3.0
So, for the sake of completeness, I'll add another solution that uses neither lambdas nor Func type (Granted that, as Matt Olenik mentioned in the comments, one could generalize the below delegates to work the same way.). For those, like me who may still be working with C# 2.0. Maybe not the best solution, but it works.
public class Example
{
public delegate void DoStuffDelecate();
public DoStuffDelecate DoStuff;
public delegate void DoStuffWithDelecate(int n);
public DoStuffWithDelecate DoStuffWithParameter;
public delegate int DoStuffWithReturnDelecate();
public DoStuffWithReturnDelecate DoStuffWithReturnValue;
}
class Program
{
static int MethodWithReturnValue()
{
return 99;
}
static void MethodForDelecate()
{
Console.WriteLine("Did Stuff");
}
static void MethodForDelecate(int n)
{
Console.WriteLine("Did Stuff with parameter " + n);
}
static void Main(string[] args)
{
var x = new Example();
x.DoStuff = MethodForDelecate;
x.DoStuffWithParameter = MethodForDelecate;
x.DoStuffWithReturnValue = MethodWithReturnValue;
x.DoStuff();
x.DoStuffWithParameter(10);
int value = x.DoStuffWithReturnValue();
Console.WriteLine("Return value " + value);
Console.ReadLine();
}
}
You are able to accomplish this with Mocking in .NET. However there is no in-language support for this feature, I think it will be available in C# 4.0. There are a number of libraries out there for Mocking, including:
Moq
RhinoMock
In short no, you have to define it as separate sub class. I think this feature is coming C# 4.0 though?
Edit: No it's not coming C# 4.0 I made that up.

Categories

Resources