Understanding Safety of Function Pointers vs. Addresses of Functions

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 7 12:54:18 PDT 2015


I'm not sure I understand the safety of function pointers vs. the 
addresses of functions. The code below illustrates the issue.

I was under the impression that pointers are not allowed in safe 
code. Naturally, I took that to also mean that function pointers 
are not allowed in safe code. Indeed, I haven't been able to pass 
a function pointer to a safe function. However, I am able to take 
the address of a function and pass that as a parameter. It seems 
to work fine for taking the address of functions and templates 
(so long as I !)

import std.stdio : writeln;
import std.traits;
import std.math;

void function_safety(T)(T fp)
{
	if (functionAttributes!fp & FunctionAttribute.safe)
		writeln("fp is safe");
	else if (functionAttributes!fp & FunctionAttribute.trusted)
		writeln("fp is trusted");
	else if (functionAttributes!fp & FunctionAttribute.system)
		writeln("fp is system");
	else
		writeln("fp is neither safe nor trusted nor system");
}

void main()
{
	function_safety(&cbrt);  //prints fp is trusted
	real function(real) fp = &cbrt;
	function_safety(fp);     //prints fp is system
}

One other related issue. The code above works for some parts of 
std.math, but it doesn't for all of it. I thought it was that 
some of them are defined in other places, so I used static import 
and tried
function_safety(&std.math.cos);
but I'm still getting this error (other people seem to have an 
issue with linking and getting it, but I'm not making any other 
change and shouldn't need to link anything).

OPTLINK (R) for Win32  Release 8.00.17
Copyright (C) Digital Mars 1989-2013  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
[path]\AppData\Local\Temp\.rdmd\rdmd-testing_fp_template_purity.d-A5DD
C99AC50E1539BAB8627648C9740B\objs\testing_fp_template_purity.exe.obj(testing_fp_
template_purity.exe)
  Error 42: Symbol Undefined _D3std4math3cosFNaNbNiNfeZe
--- errorlevel 1


More information about the Digitalmars-d-learn mailing list