C
C#12mo ago
Delta 2.1

function pointer

I need to have some kind of array of function pointer, which can be pretty big, how to encapsulate a managed Function Pointer like a Delegate, with support of arguments by ref ?
15 Replies
Angius
Angius12mo ago
You can create a delegate?
delegate int Foo(ref int x);

var foos = new Foo[]{
(ref int x) => x * 2,
(ref int x) => x * 3
};
delegate int Foo(ref int x);

var foos = new Foo[]{
(ref int x) => x * 2,
(ref int x) => x * 3
};
Something like this should work
Delta 2.1
Delta 2.1OP12mo ago
delegate would be way to expensive for my case, I don't need any dynamic resolution, and must ensure that the function is static 😅 I don't need an array to all function at the same time, but call a function based on ID
Angius
Angius12mo ago
delegate is just a way to basically alias the type of a Func or Action, whether you assign a lambda to it, or an existing method, is up to you As long as it matches the signature It's also the way to handle function pointers in C# Well, Func<>, Action<> and delegate are
Delta 2.1
Delta 2.1OP12mo ago
delegate support references on the parameter, but they are way bigger than a function pointer (I will have something like 150k of them in memory...)
alex
alex12mo ago
do you know its too big, or do you think it will be too big?
Delta 2.1
Delta 2.1OP12mo ago
I believe 24k set of at least 10 pointers is too big 🤔
333fred
333fred12mo ago
That's something like 240K of memory. That's nothing
Delta 2.1
Delta 2.1OP12mo ago
8 times this, because pointers use 8 bytes, and delegate use much more
333fred
333fred12mo ago
They don't use much more And that's still an extremely small amount of memory Measure how much memory you actually end up using, and then decide if that's a problem Don't just micro-optimize right out of the gate
MODiX
MODiX12mo ago
Angius
REPL Result: Success
unsafe {
Console.Write(sizeof(Func<int,int>));
}
unsafe {
Console.Write(sizeof(Func<int,int>));
}
Console Output
8
8
Quoted by
<@85903769203642368> from #bot-spam (click here)
Compile: 449.975ms | Execution: 23.616ms | React with ❌ to remove this embed.
Angius
Angius12mo ago
You're still looking at kilobytes A megabyte and change, at most
Delta 2.1
Delta 2.1OP12mo ago
I lose control over data used by the callback 🤨
333fred
333fred12mo ago
What?
Delta 2.1
Delta 2.1OP12mo ago
Lambda and méthods can use data other than the parameters
333fred
333fred12mo ago
Ok? You're not really explaining why this is a bad thing Indeed, a delegate can have a closure. But one of the following will be true: 1. The delegate didn't actually have a closure, so you're paying one extra pointer's worth of space to track that nothing is there. 2. The delegate did need a closure, and you are either storing that extra information somewhere else, or the function pointer doesn't work I would highly, highly suggest just seeing how much memory you're using, and decide at that point whether it's too much
Want results from more Discord servers?
Add your server