Mono集成中使用api获取当前mono 调用堆栈的方法

// 在mono源代码层级中加如下两个api 可以获取堆栈字符串 这两个api我新加的,原来没有。基于原来的代码改的。

// add by bodong
#if PLATFORM_WIN32


__declspec(dllexport) GString* __stdcall mono_debugger_get_stacktrace(int depth) { GString* text = g_string_new(0); MonoDomain* domain = mono_domain_get(); MonoJitTlsData* jit_tls = TlsGetValue(mono_jit_tls_id); MonoLMF* lmf = mono_get_lmf(); MonoJitInfo* ji, rji; gint native_offset, il_offset; gboolean managed; MonoContext ctx, new_ctx; int count = 0; char* fname; MONO_INIT_CONTEXT_FROM_FUNC(&ctx, mono_debugger_get_stacktrace); MONO_ARCH_CONTEXT_DEF mono_arch_flush_register_windows(); while (MONO_CONTEXT_GET_SP(&ctx) < jit_tls->end_of_stack) { ji = mono_find_jit_info(domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed); g_assert(ji); if (ji == (gpointer)-1) { break; } fname = mono_method_full_name(ji->method, TRUE); g_string_append_printf(text, "%s ", fname); g_free(fname); if (++count >= depth) { break; } ctx = new_ctx; } return text; } __declspec(dllexport) void __stdcall mono_debugger_free_stacktrace(GString* ptr) { if (ptr != NULL) { g_string_free(ptr, TRUE); } }
#endif

    GString的定义如下:

typedef struct {
                char* str;
                size_t len;
                size_t allocated_len;
            } GString;

  使用时只需要获取->str即可得到堆栈。用完后需要主动调用mono_debugger_free_stacktrace释放内存。

原文地址:https://www.cnblogs.com/bodong/p/13569914.html