Thread overview | ||||||
---|---|---|---|---|---|---|
|
December 04, 2008 Safe to throw away function arguments with cast? | ||||
---|---|---|---|---|
| ||||
Is it safe to cast a function(or delegate) into one that takes more arguments, causing those arguments to be ignored? Example: void fn() { } auto fptr = cast(void function(int, int))&fn; fptr(1, 2); // It seems to work with a simple test case, I'm just afraid of it blowing up at me later on. |
December 04, 2008 Re: Safe to throw away function arguments with cast? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Brian | On Thu, Dec 4, 2008 at 10:37 AM, Brian <digitalmars@brianguertin.com> wrote:
> Is it safe to cast a function(or delegate) into one that takes more
> arguments, causing those arguments to be ignored?
> Example:
>
> void fn() {
> }
>
> auto fptr = cast(void function(int, int))&fn;
> fptr(1, 2);
>
> // It seems to work with a simple test case, I'm just afraid of it blowing up at me later on.
>
No. According to the D ABI, the callee cleans the stack. So if you pass more parameters than the function expects, you'll end up trashing the stack by leaving extra values on it.
|
December 04, 2008 Re: Safe to throw away function arguments with cast? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Brian | On Thu, 04 Dec 2008 18:37:10 +0300, Brian <digitalmars@brianguertin.com> wrote:
> Is it safe to cast a function(or delegate) into one that takes more
> arguments, causing those arguments to be ignored?
> Example:
>
> void fn() {
> }
>
> auto fptr = cast(void function(int, int))&fn;
> fptr(1, 2);
>
> // It seems to work with a simple test case, I'm just afraid of it
> blowing up at me later on.
Try using type-safe alternatives:
auto fptr = (int,int) {
fn();
}
|
December 04, 2008 Re: Safe to throw away function arguments with cast? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Denis Koroskin | On Thu, Dec 4, 2008 at 12:23 PM, Denis Koroskin <2korden@gmail.com> wrote:
> On Thu, 04 Dec 2008 18:37:10 +0300, Brian <digitalmars@brianguertin.com> wrote:
>
>> Is it safe to cast a function(or delegate) into one that takes more
>> arguments, causing those arguments to be ignored?
>> Example:
>>
>> void fn() {
>> }
>>
>> auto fptr = cast(void function(int, int))&fn;
>> fptr(1, 2);
>>
>> // It seems to work with a simple test case, I'm just afraid of it blowing up at me later on.
>
> Try using type-safe alternatives:
>
> auto fptr = (int,int) {
> fn();
> }
>
That's only safe in the context of the declaring function, in D1 at least.
|
Copyright © 1999-2021 by the D Language Foundation