diff src/impl/hoofbaby/util/sharedlib.d @ 0:3425707ddbf6

Initial import (hopefully this mercurial stuff works...)
author fraserofthenight
date Mon, 06 Jul 2009 08:06:28 -0700
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/impl/hoofbaby/util/sharedlib.d	Mon Jul 06 08:06:28 2009 -0700
@@ -0,0 +1,65 @@
+/**
+ * Hoofbaby -- http://www.dsource.org/projects/hoofbaby
+ * Copyright (C) 2009 Robert Fraser
+ * 
+ * This program is free software; you can redistribute it andor
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ */
+
+module hoofbaby.util.sharedlib;
+
+public import tango.sys.SharedLib;
+
+version(Windows)    private const char[] SHARED_LIB_EXT = ".dll";
+else version(Posix) private const char[] SHARED_LIB_EXT = ".so";
+else static assert(false);
+
+private char[] stripUnderscore(char[] name)
+{
+	if(name.length && name[0] == '_')
+		return name[1 .. $];
+	return name;
+}
+
+public char[] shared_mixin(char[] libFile, char[][] functions)
+{
+	assert(functions.length % 2 == 0);
+	char[] r = "private SharedLib _lib;";
+	int numFuncs = functions.length / 2;
+	for(int i = 0; i < numFuncs; i++)
+	{
+		char[] type = functions[i * 2];
+		char[] name = stripUnderscore(functions[i * 2 + 1]);
+		if(!name.length || !type.length)
+		    continue;
+		r ~= "public static " ~ type ~ " " ~ name ~ ";";
+	}
+	r ~= "public void _loadLib() {if(_lib)return; scope(failure){_unloadLib();}";
+	r ~= "_lib = SharedLib.load(\"" ~ libFile ~ SHARED_LIB_EXT ~ "\");";
+	for(int i = 0; i < numFuncs; i++)
+	{
+		char[] nameu = functions[i * 2 + 1];
+		char[] name = stripUnderscore(nameu);
+		if(!name.length)
+		    continue;
+		r ~= name ~ " = " ~ "cast(typeof(" ~ name ~ ")) _lib.getSymbol(\"" ~ nameu ~ "\");";
+	}
+	r ~= "}";
+	r ~= "public void _unloadLib() { if(_lib){_lib.unload();}_lib=null;";
+	for(int i = 0; i < numFuncs; i++)
+	{
+		char[] name = stripUnderscore(functions[i * 2 + 1]);
+		if(!name.length)
+		    continue;
+		r ~= name ~ "=null;";
+	}
+	r ~= "}";
+	return r;
+}