View Javadoc

1   /*
2   	Copyright (c) 2009 Olivier Chafik, All Rights Reserved
3   	
4   	This file is part of JNAerator (http://jnaerator.googlecode.com/).
5   	
6   	JNAerator is free software: you can redistribute it and/or modify
7   	it under the terms of the GNU General Public License as published by
8   	the Free Software Foundation, either version 3 of the License, or
9   	(at your option) any later version.
10  	
11  	JNAerator is distributed in the hope that it will be useful,
12  	but WITHOUT ANY WARRANTY; without even the implied warranty of
13  	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  	GNU General Public License for more details.
15  	
16  	You should have received a copy of the GNU General Public License
17  	along with JNAerator.  If not, see <http://www.gnu.org/licenses/>.
18  */
19  package com.ochafik.lang.jnaerator.runtime;
20  
21  import java.lang.reflect.Method;
22  import java.util.ArrayList;
23  import java.util.Arrays;
24  import java.util.Collections;
25  import java.util.HashMap;
26  import java.util.List;
27  import java.util.Map;
28  
29  import com.sun.jna.FunctionMapper;
30  import com.sun.jna.Library;
31  import com.sun.jna.NativeLibrary;
32  import com.sun.jna.win32.StdCallFunctionMapper;
33  import com.sun.jna.win32.W32APIFunctionMapper;
34  
35  public class MangledFunctionMapper implements FunctionMapper {
36  	public static final Map<Object, Object> DEFAULT_OPTIONS;
37  	static {
38  		Map<Object, Object> m = new HashMap<Object, Object>();
39  		m.put(Library.OPTION_FUNCTION_MAPPER, new MangledFunctionMapper(
40  			new StdCallFunctionMapper()
41  		));
42  		
43  		DEFAULT_OPTIONS = Collections.unmodifiableMap(m);
44  	}
45  	public List<FunctionMapper> linked = new ArrayList<FunctionMapper>();
46  	public MangledFunctionMapper(FunctionMapper... linked ) {
47  		this.linked.addAll(Arrays.asList(linked));
48  	}
49  	public String getFunctionName(NativeLibrary library, Method method) {
50  		Mangling name = method.getAnnotation(Mangling.class);
51  		if (name != null) {
52  			for (String n : name.value()) {
53  				try {
54  					if (library.getGlobalVariableAddress(n) != null)
55  						return n;
56  					if (n.startsWith("_")) {
57  						n = n.substring(1);
58  						if (library.getGlobalVariableAddress(n) != null)
59  							return n;
60  					}
61  				} catch (Throwable ex) {
62  					ex = null;
63  				}
64  			}
65  		}
66  		if (linked != null)
67  			for (FunctionMapper fm : linked) {
68  				String n = fm.getFunctionName(library, method);
69  				if (n != null && library.getGlobalVariableAddress(n) != null)
70  					return n;
71  			}
72  		return method.getName();
73  	}
74  	
75  }