summaryrefslogtreecommitdiff
path: root/tests/library/test_loader.c
blob: a76b093cffe9826dc7a34e7ed67b1ac10f19909a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
    Copyright (C) 2010 Andreas Baumann <abaumann@yahoo.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 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.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "library/loader.h"

#include <stdlib.h>		/* for EXIT_SUCCESS, EXIT_FAILURE */
#include <stdio.h>		/* for fprintf */
#include <assert.h>		/* for assert */

int main( void ) {
	wolf_library_p library;
	wolf_error_t error;
	char errbuf[512];
	typedef int (*multiply_by_two_func)( int );
	union { multiply_by_two_func func; void *obj; } alias;
	void *symbol;
	multiply_by_two_func func;
	int res = 0;

	/* open the libray */
	library = wolf_library_load( "./testlib.so.0.0.0", &error );
	if( error != WOLF_OK ) {
		fprintf( stderr, "Error %d loading the library: %s\n",
			error, wolf_library_errmsg( error, library, errbuf, 512 ) );
		return EXIT_FAILURE;
	}

	/* fetch a known function symbol (multiply_by_two), for the reasons why naive 
	 * casting doesn't work, see:
	 * http://en.wikipedia.org/wiki/Dynamic_loading
	 */
	symbol = wolf_library_get( library, "multiply_by_two", &error );
	alias.obj = symbol;
	func = alias.func;

	/* call it */
	res = func( 7 );
	assert( res == 14 );

	/* close library */
	error = wolf_library_unload( library );
	if( error != WOLF_OK ) {
		fprintf( stderr, "Error %d unloading the library: %s\n",
			error, wolf_library_errmsg( error, library, errbuf, 512 ) );
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}