[Mono-list] NullReferenceException when calling thunk

tomason tom at creamysoft.com
Wed Jan 23 05:43:48 UTC 2013

Hello, everyone!

I'm experiencing a problem calling an unmanaged thunk into managed code. 
The first time I call the thunk, it works perfectly.  The second time, my
debugger receives a seg fault and then mono prints out that I got a
NulllReferenceException.  Calling mono_runtime_invoke on the managed method
also works perfectly, every time I call it.  I want to get thunks working
though, since performance is a concern.

I'm writing a simple app to compare performance of calling managed methods
vs calling other C++ methods, so the code I'm posting is hardly shippable,
but as far as I know, it's correct.

I init mono, register an internal call, and then run a simple C# assembly
that makes the internal call to give my C++ code a MonoObject* for the
managed class instance.  That part works perfectly, and looks like this:

g_mobj = mobj;
MonoClass *mclass = mono_object_get_class(mobj);
g_mmethod = mono_class_get_method_from_name(mclass, "Add", 2);
g_mthunk = (MonoAddFunc)mono_method_get_unmanaged_thunk(g_mmethod);

Where MonoAddFunc is defined like this:
typedef float (*MonoAddFunc)(MonoObject*, float, float);

This is the C# Add method:

public float Add(float a, float b) {
	return a + b;

This is the code for calling Add using mono_runtime_invoke (works

float a = 0.00001f, b = 0.00002f;
void *args[] = { &a, &b };
for(int i = 0; i < NUM_CALLS; ++i) {
	MonoObject *result = mono_runtime_invoke(g_mmethod, g_mobj, args, NULL);
	total += *(float*)mono_object_unbox(result);

This the code for calling Add with the thunk (fails on 2nd time through
loop, i == 1):

for(int i = 0; i < NUM_CALLS; ++i) {
	total += g_mthunk(g_mobj, 0.00001f, 0.00002f);

I wrote another test app where I created the thunk the same way, and it
works fine, but the other method I called in that app had no parameters.

Any help will be greatly appreciated!


View this message in context: http://mono.1490590.n4.nabble.com/NullReferenceException-when-calling-thunk-tp4658230.html
Sent from the Mono - General mailing list archive at Nabble.com.

More information about the Mono-list mailing list