aboutsummaryrefslogtreecommitdiff
path: root/clr.cpp
blob: 72185f0e2628f9281c4c5b4389ca1d7b3ac9871e (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
// mono
extern "C" {
#include <mono/jit/jit.h>
#include <mono/metadata/object.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/class.h>
#include <mono/metadata/metadata.h>
}

#ifdef _MSC_VER
#pragma warning(disable: 4091)
#endif
#include <m_pd.h>

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <io.h> // for _close

#include <map>

#if 0

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// OLD VERSION
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////


#include <time.h>
#include <math.h>


#define MAX_SELECTORS 256
#define MAX_OUTLETS 32

void *clr_new(t_symbol *s, int argc, t_atom *argv);

typedef struct _clr
{
    t_object x_obj; // myself
	t_outlet *l_out;
	t_symbol *assemblyname;
	t_symbol *filename;
	int loaded;
	// mono stuff
	MonoAssembly *assembly;
	MonoObject *obj;
	MonoImage *image;
	MonoMethod *method, *setUp, *manageBang, *manageSymbol, *manageFloat, *manageList;
	MonoClass *klass;
	int n;

	// TODO: dynamic memory allocation
	selectorList selectors[MAX_SELECTORS];
	outletList outlets[MAX_OUTLETS];

} t_clr;

// list of mono methods
typedef struct
{
	char *sel; // the selector
	MonoMethod *func; // the function
	int type;
//	selectorList *next; // next element of the list
} selectorList;

// list of outlets
typedef struct 
{
	t_outlet *outlet_pointer;
//	outletList *next; // next element of the list
} outletList;

// simplyfied atom
typedef enum
{
    A_S_NULL=0,
    A_S_FLOAT=1,
    A_S_SYMBOL=2,
}  t_atomtype_simple;

typedef struct 
{
	//t_atomtype_simple a_type;
	int a_type;
	float float_value;
	MonoString *string_value;

} atom_simple;




// mono functions

static void mono_clean(t_clr *x)
{
	// clean up stuff
	//mono_jit_cleanup (x->domain);
	//mono_domain_free(x->domain);
}

void registerMonoMethod(void *x, MonoString *selectorString, MonoString *methodString, int type);
void createInlet(void *x1, MonoString *selectorString, int type);
void createOutlet(void *x1, int type);
void out2outlet(void *x1, int outlet, int atoms_length, MonoArray *array);
void post2pd(MonoString *mesString);
void error2pd(MonoString *mesString);


// load the variables and init mono
static void mono_load(t_clr *x, int argc, t_atom *argv)
{
//	const char *file="D:\\Davide\\cygwin\\home\\Davide\\externalTest1.dll";
	//const char *file="External.dll";
	
	MonoMethod *m = NULL, *ctor = NULL, *fail = NULL, *mvalues;
	MonoClassField *classPointer;
	gpointer iter;
	gpointer *args;
	int val;
	int i,j;
	int params;
	t_symbol *strsymbol;
	atom_simple *listparams;

	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}

	// prepare the selectors list
	for (i=0; i<MAX_SELECTORS; i++)
	{
		x->selectors[i].sel = 0;
		x->selectors[i].func = 0;
	}
	// and the outlets list
	for (i=0; i<MAX_OUTLETS; i++)
	{
		x->outlets[i].outlet_pointer = 0;
	}

	//mono_set_dirs (NULL, NULL);
	//mono_config_parse (NULL);

	//mono_jit_init (random_name_str);
//	x->domain = mono_domain_get();
	// all done without errors
	x->loaded = 1;

}

/*
// call the method
static void clr_bang(t_clr *x) {

	gpointer args [2];
	int val;
	MonoObject *result;

	val = x->n;
	args [0] = &val;

	if (x->method)
	{
		result = mono_runtime_invoke (x->method, x->obj, args, NULL);
		val = *(int*)mono_object_unbox (result);
		x->n = val;
	//	outlet_float(x->l_out, (float) x->n);
	}


}
*/

// finds a method from its name
void findMonoMethod( MonoClass *klass, char *function_name, MonoMethod **met)
{
	int trovato;
	MonoMethod *m = NULL;
	gpointer iter;
	iter = NULL;
	while (m = mono_class_get_methods (klass, &iter)) 
	{
		if (strcmp (mono_method_get_name (m), function_name) == 0) 
		{
			*met = m;
//printf("%s trovata\n", function_name);
			return;
		} 	
	}
}

void clr_free(t_clr *x)
{
	mono_clean(x);
}

static void clr_method_bang(t_clr *x) 
{
	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}
	if (x->manageBang)
	{
		mono_runtime_invoke (x->manageBang, x->obj, NULL, NULL);
	}
}

static void clr_method_symbol(t_clr *x, t_symbol *sl) 
{
	gpointer args [1];
	MonoString *strmono;
	strmono = mono_string_new (monodomain, sl->s_name);
	args[0] = &strmono;
	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}
	if (x->manageSymbol)
	{
		mono_runtime_invoke (x->manageSymbol, x->obj, args, NULL);
	}
}

static void clr_method_float(t_clr *x, float f) 
{
	gpointer args [1];
	args [0] = &f;
	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}
	if (x->manageFloat)
	{
		mono_runtime_invoke (x->manageFloat, x->obj, args, NULL);
	}
}

// here i look for the selector and call the right mono method
static void clr_method_list(t_clr *x, t_symbol *sl, int argc, t_atom *argv)
{
	gpointer args [2];
	int valInt;
	float valFloat;

	int i;
	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}

	// check if a selector is present !
	//printf("clr_manage_list, got symbol = %s\n", sl->s_name);
	if (strcmp("list", sl->s_name) == 0)
	{
		printf("lista senza selector");
		if (x->manageList)
		{
			gpointer args [1];
			MonoString *stringtmp;
			double *floattmp;
			t_atomtype_simple *typetmp;
			t_symbol *strsymbol;
			MonoArray *atoms;
			atom_simple *atom_array;
			int j;		
			char strfloat[256], strnull[256];
			sprintf(strfloat, "float");
			sprintf(strnull, "null");
			atom_array = malloc(sizeof(atom_simple)*argc);
			atoms = mono_array_new (monodomain, clr_atom, argc);
			for (j=0; j<argc; j++)
			{
				switch ((argv+j)->a_type)
				{
				case A_FLOAT:
					atom_array[j].a_type =  A_S_FLOAT;
					atom_array[j].float_value = (double) atom_getfloat(argv+j);
					atom_array[j].string_value = mono_string_new (monodomain, strfloat);
					break;
				case A_SYMBOL:
					atom_array[j].a_type =  A_S_SYMBOL;
					strsymbol = atom_getsymbol(argv+j);
					atom_array[j].string_value = mono_string_new (monodomain, strsymbol->s_name);
					atom_array[j].float_value = 0;
					break;
				default:
					atom_array[j].a_type =  A_S_NULL;
					atom_array[j].float_value = 0;
					atom_array[j].string_value = mono_string_new (monodomain, strnull);
				}
				mono_array_set (atoms, atom_simple , j, atom_array[j]);
			}

			args[0] = atoms;
			mono_runtime_invoke (x->manageList, x->obj, args, NULL);
			return;
		} else
		{
			error("you did not specified a function to call for lists without selectors");
			return;
		}
	}
	for (i=0; i<MAX_SELECTORS; i++)
	{
		if (strcmp(x->selectors[i].sel, sl->s_name) == 0)
		{
			// I've found the selector!
			if (x->selectors[i].func)
			{
				// ParametersType {None = 0, Float=1, Symbol=2, List=3};
				switch (x->selectors[i].type)
				{
				case 0:
					mono_runtime_invoke (x->selectors[i].func, x->obj, NULL, NULL);
					break;
				case 1:
					{
						gpointer args [1];
						float val = atom_getfloat(argv);
						args[0] = &val;
						mono_runtime_invoke (x->selectors[i].func, x->obj, args, NULL);
						break;
					}
				case 2:
					{
						gpointer args [1];
						t_symbol *strsymbol;
						MonoString *strmono;
						strsymbol = atom_getsymbol(argv);
						strmono = mono_string_new (monodomain, strsymbol->s_name);
						args[0] = &strmono;
						mono_runtime_invoke (x->selectors[i].func, x->obj, args, NULL);
						// memory leak ?
						break;
					}
				case 3:
					{
						gpointer args [1];
						MonoString *stringtmp;
						double *floattmp;
						t_atomtype_simple *typetmp;
						t_symbol *strsymbol;
						MonoArray *atoms;
						atom_simple *atom_array;
						int j;		
						char strfloat[256], strnull[256];
						sprintf(strfloat, "float");
						sprintf(strnull, "null");
						atom_array = malloc(sizeof(atom_simple)*argc);
						atoms = mono_array_new (monodomain, clr_atom, argc);
						for (j=0; j<argc; j++)
						{
							switch ((argv+j)->a_type)
							{
							case A_FLOAT:
								atom_array[j].a_type =  A_S_FLOAT;
								atom_array[j].float_value = (double) atom_getfloat(argv+j);
								atom_array[j].string_value = mono_string_new (monodomain, strfloat);
								break;
							case A_SYMBOL:
								atom_array[j].a_type =  A_S_SYMBOL;
								strsymbol = atom_getsymbol(argv+j);
								atom_array[j].string_value = mono_string_new (monodomain, strsymbol->s_name);
								atom_array[j].float_value = 0;
								break;
							default:
								atom_array[j].a_type =  A_S_NULL;
								atom_array[j].float_value = 0;
								atom_array[j].string_value = mono_string_new (monodomain, strnull);
							}
							mono_array_set (atoms, atom_simple , j, atom_array[j]);
						}

						args[0] = atoms;
						mono_runtime_invoke (x->selectors[i].func, x->obj, args, NULL);
						break;
					}
				}
				return;
			}
		}
		if (x->selectors[i].func == 0)
			i = MAX_SELECTORS;
	}
	error("clr: selector not recognized");
}

// this function is called by mono when it wants to register a selector callback
void registerMonoMethod(void *x1, MonoString *selectorString, MonoString *methodString, int type)
{
	
	char *selCstring, *metCstring;
	MonoMethod *met;
	t_clr *x;
	int this_selector, i;
	//int ret;

	
    selCstring = mono_string_to_utf8 (selectorString);
	metCstring = mono_string_to_utf8 (methodString);
	
	x = (t_clr *)x1;

	//ret = 0;
	met = 0;
	findMonoMethod( x->klass, metCstring, &met);

	if (!met)
	{
		error("method not found!");
		return;
	}

	//post("registerMonoMethod: associating %s to %s", selCstring, metCstring);

	if (selectorString->length == 0)
	{
		switch (type)
		{
		case 1: // float
			x->manageFloat = met;
			break;
		case 2: // string
			x->manageSymbol = met;
			break;
		case 3: // list
			x->manageList = met;
			break;
		case 4: // bang
			x->manageBang = met;
			break;
		}
	}

	this_selector = MAX_SELECTORS;
	for (i = 0; i < MAX_SELECTORS; i++)
	{
		if (x->selectors[i].func == 0)
		{
			// i found the first empty space
			this_selector = i;
			i = MAX_SELECTORS;
		}
		
	}
	if (this_selector == MAX_SELECTORS)
	{
		error("not enough space for selectors! MAX_SELECTORS = %i", MAX_SELECTORS);
		return;
	}

	x->selectors[this_selector].sel = selCstring;
	x->selectors[this_selector].func = met;
	x->selectors[this_selector].type = type;

	class_addmethod(clr_class, (t_method)clr_method_list, gensym(selCstring), A_GIMME, 0);


}

// this function is called by mono when it wants to create a new inlet
void createInlet(void *x1, MonoString *selectorString, int type)
{
	// public enum ParametersType {None = 0, Float=1, Symbol=2, List=3, Bang=4, Generic=5};
	char *selCstring;
	char typeString[256];
	t_clr *x;

    selCstring = mono_string_to_utf8 (selectorString);	
	x = (t_clr *)x1;
	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}
	switch (type)
	{
	case 1:
		sprintf(typeString, "float");
		break;
	case 2:
		sprintf(typeString, "symbol");
		break;
	case 3:
		sprintf(typeString, "list");
		break;
	case 4:
		sprintf(typeString, "bang");
		break;
	default:
		sprintf(typeString, "");
		break;
	}
	// create the inlet
	inlet_new(&x->x_obj, &x->x_obj.ob_pd, gensym(typeString), gensym(selCstring));
}

// this function is called by mono when it wants to create a new outlet
void createOutlet(void *x1, int type)
{
	t_clr *x;
	int i = 0;
	char typeString[256];
	x = (t_clr *)x1;
	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}
	// public enum ParametersType {None = 0, Float=1, Symbol=2, List=3, Bang=4, Generic=5};
	switch (type)
	{
	case 1:
		sprintf(typeString, "float");
		break;
	case 2:
		sprintf(typeString, "symbol");
		break;
	case 3:
		sprintf(typeString, "list");
		break;
	case 4:
		sprintf(typeString, "bang");
		break;
	default:
		sprintf(typeString, "");
		break;
	}

	while (i < MAX_OUTLETS)
	{
		if (x->outlets[i].outlet_pointer == 0)
		{
			// empty space found!
			x->outlets[i].outlet_pointer = outlet_new(&x->x_obj, gensym(typeString));
			return;
		}
		i++;
	}
	error("the maximum number of outlets has been reached (%i)", MAX_OUTLETS);
	
}

// out to outlet
void out2outlet(void *x1, int outlet, int atoms_length, MonoArray *array)
{
	t_clr *x;
	t_atom *lista;
	atom_simple *atoms;
	int n;
	x = (t_clr *)x1;
	if (x->loaded == 0)
	{
		error("assembly not specified");
		return;
	}
	if ((outlet>MAX_OUTLETS) || (outlet<0))
	{
		error("outlet number out of range, max is %i", MAX_OUTLETS);
		return;
	}
	if (x->outlets[outlet].outlet_pointer == 0)
	{
		error("outlet %i not registered", outlet);
		return;
	}
	lista = (t_atom *) malloc(sizeof(t_atom) * atoms_length);
	atoms = (atom_simple *) malloc(sizeof(atom_simple) * atoms_length);
	for (n=0; n<atoms_length; n++)
	{
		char *mesCstring;
		atoms[n] = mono_array_get(array, atom_simple, n);
		switch (atoms[n].a_type)
		{
			case A_S_NULL:
				SETFLOAT(lista+n, (float) 0);
				break;
			case A_S_FLOAT:
				SETFLOAT(lista+n, (float) atoms[n].float_value);
				break;
			case A_S_SYMBOL:
				mesCstring = mono_string_to_utf8 (atoms[n].string_value);
				SETSYMBOL(lista+n, gensym(mesCstring));
				break;
		}

	}
	outlet_anything(x->outlets[outlet].outlet_pointer,
					gensym("list") ,
					atoms_length, 
					lista);
	free(lista);
}

// this function is called by mono when it wants post messages to pd
void post2pd(MonoString *mesString)
{
	
	char *mesCstring;
    mesCstring = mono_string_to_utf8 (mesString);
	post(mesCstring);
	
}

// this function is called by mono when it wants to post errors to pd
void error2pd(MonoString *mesString)
{
	
	char *mesCstring;
    mesCstring = mono_string_to_utf8 (mesString);
	error(mesCstring);
}
/*
//void ext_class_addbang(const char *funcName)
void ext_class_addbang(t_method funcName)
{
//	class_addbang(clr_class, (t_method)clr_bang);
	class_addbang(clr_class, funcName);
}*/

void *clr_new(t_symbol *s, int argc, t_atom *argv)
{

	int i;
	time_t a;
    t_clr *x = (t_clr *)pd_new(clr_class);

	char strtmp[256];
	x->manageBang = 0;
	x->manageSymbol = 0;
	x->manageFloat = 0;
	x->manageList = 0;
	
	if (argc==0)
	{
		x->loaded = 0;
		error("clr: you must provide a class name as the first argument");
		return (x);
	}
	x->loaded = 1;
	x->assemblyname = atom_gensym(argv);
	
	if (argc<2)
	{
		// only main class passed
		// filename by default
		sprintf(strtmp, "%s.dll", x->assemblyname->s_name);
		x->filename = gensym(strtmp);
        printf(" used did not specified filename, I guess it is %s\n", strtmp);
	} else
	{
		x->filename = atom_gensym(argv+1);
	}

    x->obj = mono_object_new (monodomain, x->klass);

	// load mono, init the needed vars
//	mono_load(x, argc, argv);
	// now call the class constructor
	if (ctor)
	{
		args = malloc(sizeof(gpointer)*params);
		listparams = malloc(sizeof(atom_simple)*params);
		for (j=2; j<argc; j++)
		{
			switch ((argv+j)->a_type)
			{
			case A_FLOAT:
				listparams[j-2].a_type =  A_S_FLOAT;
				listparams[j-2].float_value = (double) atom_getfloat(argv+j);
				args[j-2] = &(listparams[j-2].float_value);
				break;
			case A_SYMBOL:
				listparams[j-2].a_type =  A_S_SYMBOL;
				strsymbol = atom_getsymbol(argv+j);
				listparams[j-2].string_value = mono_string_new (monodomain, strsymbol->s_name);
				args[j-2] = listparams[j-2].string_value;
				break;
			}
		}
		mono_runtime_invoke (ctor, x->obj, args, NULL);
		free(listparams);
		free(args);
	} else
	{
		error("%s doesn't have a constructor with %i parameters!",x->assemblyname->s_name, params);
	}


    return (x);
}

#endif

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// NEW VERSION
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static MonoDomain *monodomain;
static MonoClass *clr_atom,*clr_symbol;
static MonoClassField *clr_symbol_ptr;
//static MonoMethod *clr_symbol_ctor;
static MonoMethodDesc *clr_desc_main,*clr_desc_ctor;
static MonoMethodDesc *clr_desc_bang,*clr_desc_float,*clr_desc_symbol,*clr_desc_pointer,*clr_desc_list,*clr_desc_anything;

typedef std::map<t_symbol *,MonoMethod *> ClrMethodMap;

// this is the class structure
// holding the pd and mono class
// and our CLR method pointers
typedef struct
{
    t_class *pd_class;
    MonoClass *mono_class;
    MonoClassField *mono_obj_field;
    MonoMethod *mono_ctor;
    MonoMethod *method_bang,*method_float, *method_symbol,*method_list,*method_pointer,*method_anything;
//    ClrMethodMap *methods;
} t_clr_class;

typedef std::map<t_symbol *,t_clr_class *> ClrMap;
// this holds the class name to class structure association
static ClrMap clr_map;

// this is the class to be setup (while we are in the CLR static Main method)
static t_clr_class *clr_setup_class = NULL;

// this is the class instance object structure
typedef struct
{
    t_object pd_obj; // myself
    t_clr_class *clr_clss; // pointer to our class structure
    MonoObject *mono_obj;
} t_clr;



static void clr_method_bang(t_clr *x) 
{
    assert(x && x->clr_clss && x->clr_clss->method_bang);
    mono_runtime_invoke(x->clr_clss->method_bang,x->mono_obj,NULL,NULL);
}

static void clr_method_float(t_clr *x,t_float f) 
{
    assert(x && x->clr_clss && x->clr_clss->method_float);
	gpointer args = &f;
    mono_runtime_invoke(x->clr_clss->method_float,x->mono_obj,&args,NULL);
}

static void clr_method_symbol(t_clr *x,t_symbol *s) 
{
    assert(x && x->clr_clss && x->clr_clss->method_symbol);
    MonoObject *symobj = mono_object_new(monodomain,clr_symbol);
//	gpointer args = &s;
//    mono_runtime_invoke(clr_symbol_ctor,symobj,&args,NULL);
    // setting the field directly doesn't seem to work?!
    mono_field_set_value(symobj,clr_symbol_ptr,s);
	gpointer args = symobj;
    mono_runtime_invoke(x->clr_clss->method_symbol,x->mono_obj,&args,NULL);
}

static void clr_method_list(t_clr *x,int argc, t_atom *argv)
{
    assert(x && x->clr_clss && x->clr_clss->method_list);
}

static void clr_method_pointer(t_clr *x,t_gpointer *ptr)
{
    assert(x && x->clr_clss && x->clr_clss->method_pointer);
}

static void clr_method_anything(t_clr *x,t_symbol *sl, int argc, t_atom *argv)
{
#if 0
    assert(x && x->clr_clss);
    ClrMethodMap *methods = x->clr_clss->methods;
    if(methods) {
        ClrMethodMap::iterator it = methods->find(sl);
        if(it != methods->end()) {
            // \TODO call m
            return;
        }
    }
    if(x->clr_clss->method_anything) {
         // \TODO call methodanything
    }
    else
        post("CLR - no method for %s found",sl->s_name);
#else
    assert(x && x->clr_clss && x->clr_clss->method_anything);
#endif
}


// this function is called by mono when it wants post messages to pd
static void PD_Post(MonoString *str)
{
	post("%s",mono_string_to_utf8(str));	
}

// this function is called by mono when it wants post messages to pd
static void PD_PostError(MonoString *str)
{
	error("%s",mono_string_to_utf8(str));	
}

// this function is called by mono when it wants post messages to pd
static void PD_PostBug(MonoString *str)
{
	bug("%s",mono_string_to_utf8(str));	
}

// this function is called by mono when it wants post messages to pd
static void PD_PostVerbose(int lvl,MonoString *str)
{
	verbose(lvl,"%s",mono_string_to_utf8(str));	
}

static void *PD_GenSym(MonoString *str)
{
	return gensym(mono_string_to_utf8(str));	
}

static MonoString *PD_EvalSym(MonoObject *symobj)
{
    t_symbol *sym;
    mono_field_get_value(symobj,clr_symbol_ptr,&sym);
    return mono_string_new(monodomain,sym->s_name);
}


#if 0
// this function is called by mono when it wants post messages to pd
static void PD_AddMethod(MonoObject *symobj,MonoObject *obj)
{
    assert(clr_setup_class);

//    char *tag = mono_string_to_utf8(str);
//	post("register method %s",tag);
    t_symbol *sym;
    mono_field_get_value(symobj,clr_symbol_ptr,&sym);

    // \TODO convert from obj
    MonoMethod *m = NULL;

    if(sym == &s_bang) {
        if(!clr_setup_class->method_bang)
    	    class_addbang(clr_setup_class->pd_class,clr_method_bang);
        clr_setup_class->method_bang = m;
    }
    else if(sym == &s_float) {
        if(!clr_setup_class->method_bang)
    	    class_addfloat(clr_setup_class->pd_class,clr_method_float);
        clr_setup_class->method_bang = m;
    }
    else if(sym == &s_symbol) {
        if(!clr_setup_class->method_symbol)
    	    class_addsymbol(clr_setup_class->pd_class,clr_method_symbol);
        clr_setup_class->method_symbol = m;
    }
    else if(sym == &s_list) {
        if(!clr_setup_class->method_list)
    	    class_addlist(clr_setup_class->pd_class,clr_method_list);
        clr_setup_class->method_list = m;
    }
    else if(sym == &s_pointer) {
        if(!clr_setup_class->method_pointer)
        	class_addpointer(clr_setup_class->pd_class,clr_method_pointer);
        clr_setup_class->method_pointer = m;
    }
    else if(sym == &s_) {
        if(!clr_setup_class->method_anything && !clr_setup_class->methods) // only register once!
	        class_addanything(clr_setup_class->pd_class,clr_method_anything);
        clr_setup_class->method_anything = m;
    }
    else {
        if(!clr_setup_class->methods) {
            // no methods yet
            clr_setup_class->methods = new ClrMethodMap;
            if(!clr_setup_class->method_anything) // only register once!
    	        class_addanything(clr_setup_class->pd_class,clr_method_anything);
        }

        // add tag to map
        (*clr_setup_class->methods)[sym] = m;
    }
}
#endif

void *clr_new(t_symbol *classname, int argc, t_atom *argv)
{
    // find class name in map
    ClrMap::iterator it = clr_map.find(classname);
    if(it == clr_map.end()) {
        error("CLR class %s not found",classname->s_name);
        return NULL;
    }

    t_clr_class *clss = it->second;

    // make instance
    t_clr *x = (t_clr *)pd_new(clss->pd_class);
    x->mono_obj = mono_object_new (monodomain,clss->mono_class);
    if(!x->mono_obj) {
        pd_free((t_pd *)x);
        error("CLR class %s could not be instantiated",classname->s_name);
        return NULL;
    }

    // store class pointer
    x->clr_clss = clss;

    // store our object pointer in External::ptr member
    mono_field_set_value(x->mono_obj,clss->mono_obj_field,x);

    // ok, we have an object - look for constructor
	if(clss->mono_ctor) {
        // call static Main method
        MonoObject *ret = mono_runtime_invoke(clss->mono_ctor,x->mono_obj,NULL,NULL);
        if(ret) {
            post("Warning: returned value from %s::.ctor ignored",classname->s_name);
            // ??? do we have to mark ret as free?
        }
    }
    else
        post("Warning: no %s.Main method found",classname);

    return x;
}

void clr_free(t_clr *x)
{
}

static int classloader(char *dirname, char *classname)
{
    t_clr_class *clr_class = NULL;
    t_symbol *classsym;
    MonoAssembly *assembly;
    MonoImage *image;
    MonoMethod *method;

    char dirbuf[MAXPDSTRING],*nameptr;
    // search for classname.dll in the PD path
    int fd;
    if ((fd = open_via_path(dirname, classname, ".dll", dirbuf, &nameptr, MAXPDSTRING, 1)) < 0)
        // not found
        goto bailout;

    // found
    _close(fd);

    clr_class = (t_clr_class *)getbytes(sizeof(t_clr_class));

//    clr_class->methods = NULL;

    // try to load assembly
    char path[MAXPDSTRING];
    strcpy(path,dirname);
    strcat(path,"/");
//    strcat(path,dirbuf);
//    strcat(path,"/");
    strcat(path,nameptr);

    assembly = mono_domain_assembly_open(monodomain,path);
	if(!assembly) {
		error("clr: file %s couldn't be loaded!",path);
		goto bailout;
	}

    image = mono_assembly_get_image(assembly);
    assert(image);

    // try to find class
    // "" means no namespace
	clr_class->mono_class = mono_class_from_name(image,"",classname);
	if(!clr_class->mono_class) {
		error("Can't find %s class in %s\n",classname,mono_image_get_filename(image));
		goto bailout;
	}

    clr_class->mono_obj_field = mono_class_get_field_from_name(clr_class->mono_class,"ptr");
    assert(clr_class->mono_obj_field);

    // ok

	post("CLR class %s loaded",classname);

    // make new class (with classname)
    classsym = gensym(classname);
    clr_class->pd_class = class_new(classsym,(t_newmethod)clr_new,(t_method)clr_free, sizeof(t_clr), CLASS_DEFAULT, A_GIMME, 0);

    // find static Main method

    method = mono_method_desc_search_in_class(clr_desc_main,clr_class->mono_class);
	if(method) {
        // set current class
        clr_setup_class = clr_class;

        // call static Main method
        MonoObject *ret = mono_runtime_invoke(method,NULL,NULL,NULL);

        // unset current class
        clr_setup_class = NULL;

        if(ret) {
            post("CLR - Warning: returned value from %s.Main ignored",classname);
            // ??? do we have to mark ret as free?
        }
    }
    else
        post("CLR - Warning: no %s.Main method found",classname);

    // find and save constructor
    clr_class->mono_ctor = mono_method_desc_search_in_class(clr_desc_ctor,clr_class->mono_class);

    // find && register methods
    if((clr_class->method_bang = mono_method_desc_search_in_class(clr_desc_bang,clr_class->mono_class)) != NULL)
        class_addbang(clr_class->pd_class,clr_method_bang);
    if((clr_class->method_float = mono_method_desc_search_in_class(clr_desc_float,clr_class->mono_class)) != NULL)
        class_addfloat(clr_class->pd_class,clr_method_float);
    if((clr_class->method_symbol = mono_method_desc_search_in_class(clr_desc_symbol,clr_class->mono_class)) != NULL)
        class_addsymbol(clr_class->pd_class,clr_method_symbol);
//    if((clr_class->method_pointer = mono_class_get_method_from_name(clr_class->mono_class,"MethodPointer",1)) != NULL)
    if((clr_class->method_pointer = mono_method_desc_search_in_class(clr_desc_pointer,clr_class->mono_class)) != NULL)
        class_addpointer(clr_class->pd_class,clr_method_pointer);
    if((clr_class->method_list = mono_method_desc_search_in_class(clr_desc_list,clr_class->mono_class)) != NULL)
        class_addlist(clr_class->pd_class,clr_method_list);
    if((clr_class->method_anything = mono_method_desc_search_in_class(clr_desc_anything,clr_class->mono_class)) != NULL)
        class_addanything(clr_class->pd_class,clr_method_anything);


    // put into map
    clr_map[classsym] = clr_class;

    post("Loaded class %s OK",classname);

    return 1;

bailout:
    if(clr_class) freebytes(clr_class,sizeof(t_clr_class));

    return 0;
}

extern "C"
#ifdef _MSC_VER
__declspec(dllexport) 
#endif
void clr_setup(void)
{
#ifdef _WIN32
    // set mono paths
    const char *monopath = getenv("MONO_PATH");
    if(!monopath) {
        error("CLR - Please set the MONO_PATH environment variable to the folder of your MONO installation - CLR not loaded!");
        return;
    }
    
    char tlib[256],tconf[256];
    strcpy(tlib,monopath);
    strcat(tlib,"/lib");
    strcpy(tconf,monopath);
    strcat(tconf,"/etc");
    mono_set_dirs(tlib,tconf);
#endif

    monodomain = mono_jit_init("PureData");
	if(monodomain) {
    /*	
	    // add mono to C hooks
	    mono_add_internal_call ("PureData.pd::RegisterSelector", registerMonoMethod);
	    mono_add_internal_call ("PureData.pd::ToOutlet", out2outlet);
	    mono_add_internal_call ("PureData.pd::PostMessage", post2pd);
	    mono_add_internal_call ("PureData.pd::ErrorMessage", error2pd);
	    mono_add_internal_call ("PureData.pd::CreateOutlet", createOutlet);
	    mono_add_internal_call ("PureData.pd::CreateInlet", createInlet);
    */
//	    mono_add_internal_call ("PureData.Core::AddMethod", PD_AddMethod);

        mono_add_internal_call("PureData.Core::Post",(const void *)PD_Post);
	    mono_add_internal_call("PureData.Core::PostError",(const void *)PD_PostError);
	    mono_add_internal_call("PureData.Core::PostBug",(const void *)PD_PostBug);
	    mono_add_internal_call("PureData.Core::PostVerbose",(const void *)PD_PostVerbose);

	    mono_add_internal_call("PureData.Core::GenSym", PD_GenSym);
	    mono_add_internal_call("PureData.Core::EvalSym", PD_EvalSym);


        MonoAssembly *assembly = mono_domain_assembly_open (monodomain, "PureData.dll");
	    if(!assembly) {
		    error("clr: assembly PureData.dll not found!");
		    return;
	    }

	    MonoImage *image = mono_assembly_get_image(assembly);
        assert(image);

        // load important classes
        clr_atom = mono_class_from_name(image,"PureData","Atom");
        assert(clr_atom);
        clr_symbol = mono_class_from_name(image,"PureData","Symbol");
        assert(clr_symbol);
        clr_symbol_ptr = mono_class_get_field_from_name(clr_symbol,"ptr");
        assert(clr_symbol_ptr);
//        MonoMethodDesc *d = mono_method_desc_new("::.ctor(System.IntPtr)",FALSE);
//        assert(d);
//        clr_symbol_ctor = mono_method_desc_search_in_class(d,clr_symbol);
//        assert(clr_symbol_ctor);

        clr_desc_main = mono_method_desc_new("::Main",FALSE);
        assert(clr_desc_main);
        clr_desc_ctor = mono_method_desc_new("::.ctor",FALSE);
        assert(clr_desc_ctor);

        clr_desc_bang = mono_method_desc_new(":MethodBang",FALSE);
        assert(clr_desc_bang);
        clr_desc_float = mono_method_desc_new(":MethodFloat",FALSE);
        assert(clr_desc_float);
        clr_desc_symbol = mono_method_desc_new(":MethodSymbol",FALSE);
        assert(clr_desc_symbol);
        clr_desc_pointer = mono_method_desc_new(":MethodPointer",TRUE);
        assert(clr_desc_pointer);
        clr_desc_list = mono_method_desc_new(":MethodList",TRUE);
        assert(clr_desc_list);
        clr_desc_anything = mono_method_desc_new(":MethodAnything",TRUE);
        assert(clr_desc_anything);

        // install loader hook
        sys_loader(classloader);

        // ready!
	    post("CLR - (c) Davide Morelli, Thomas Grill");
    }
    else
		error("clr: mono domain couldn't be initialized!");
}