[Mono-devel-list] [Embedding Mono] Accessing Fields

Friedrich Priewasser priewasser at gmx.at
Tue Aug 3 19:53:10 EDT 2004


Hi,

I'm trying to access a field of a C# struct (from C), but i don't get the  
expected result.
My programm should set i to 11 and then write out this value by calling  
"Write()".
If T is a class this works, but if T is a struct I dont't get "11".
By calling mono_field_set with an address reduced by 8 (size of a  
MonoObject?) it works
(field offset of "i" is 8, using class and using struct)

Reducing the address by 8 is not very clean,
so, can anyone help me and tell me what i've done wrong?

My C# struct:

public struct T{
	public int i;
	public void Write(){
	  System.Console.WriteLine(i);
	}
}


The C code:

#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>

int main(){
   MonoDomain *domain;
   MonoAssembly *assembly;
   MonoImage *image;
   MonoClass *klass;
   MonoObject *object;
   MonoClassField *field;
   MonoMethodDesc *desc;
   MonoMethod *method;
   int val;

   domain = mono_jit_init ("Domain");
   assembly = mono_domain_assembly_open (domain, "T.DLL");;
   image = mono_assembly_get_image(assembly);
   klass = mono_class_from_name(image, "", "T");
   mono_class_init (klass);
   object = mono_object_new (domain, klass);

   val=11;
   field = mono_class_get_field_from_name(klass,"i");
   mono_field_set_value(object,field,&val);
   //mono_field_set_value((MonoObject*)((void*)object-8),field,&val);

   desc = mono_method_desc_new (":Write()",TRUE);
   method = mono_method_desc_search_in_class (desc, klass);
   mono_runtime_invoke(method,object,NULL,NULL);

   return 0;
}



More information about the Mono-devel-list mailing list