inverse of std.demangle?

Adam D. Ruppe destructionator at gmail.com
Wed Jul 10 12:31:28 PDT 2013


On Wednesday, 10 July 2013 at 19:03:22 UTC, Timothee Cour wrote:
> How would that work, since this is runtime only?

Take a pointer with the right type and then attach the rest of 
the name to it. Given:

int foo(int a, string) { return a;}

void main() {
         int function(int, string) fooPtr;
         pragma(msg, foo.mangleof);
         pragma(msg, typeof(fooPtr).mangleof);
}

You get:

_D6test303fooFiAyaZi
PFiAyaZi


The first part of the full name is pretty simple: _Dnamehere, 
where namehere is length pf the part, then the part.

length 6, string "test30
length 3, string "foo"

total name: test30.foo



Then after that, comes the type: a 'F'unction that returns 'int' 
with arguments (in reverse order) 'A'rray of immutable ('y') char 
('a'), then the 'Z' final argument 'i'nt.


The second line shows a 'P'ointer to that same typed symbol.


If you want to get the foo function out of a library, you'd 
probably go:


fooptr = cast(typeof(fooptr)) dlsym(handle, 
"_D6test303fooFiAyaZi");


Then you can use fooptr. Without knowing the static type of the 
function though, it isn't safe to use - you could pass it wrong 
arguments and ruin your day. So having the statically typed 
function pointer is very useful.


Since we have that, we can get a name from the user and put it 
together:


fooptr = cast(typeof(fooptr)) dlsym(handle, "_D" ~ 
mangleName("test30.foo") ~ typeof(fooptr).mangleof[1 .. $]);

Cut the 'P' off the fooptr mangle and attach that to the name's 
mangle, and we have the full name.



If you want to ask for the type from the user too, what I'd do is 
compare it against the various options you know how to handle:


foreach(type; TypeTuple!(int function(int, string), int 
function() /* and whatever else you want */)  {
     if(userEnteredString == type.stringof) {
         type ptr = cast(type) dlsym(handle, "_D" ~ 
mangleName(userEnteredName) ~ type.mangleof[1 .. $]);
         if(ptr is null) throw new Exception("not found in 
library");
     }
}

/* otherwise, throw that the user entered type isn't supported */




So, of course, this limits you to the list of supported function 
signatures, but I think you realistically are anyway since 
getting the ABI right at runtime from arbitrary input isn't going 
to be easy.


More information about the Digitalmars-d-learn mailing list