server-modloader icon indicating copy to clipboard operation
server-modloader copied to clipboard

Add hook macro & std::string api for C

Open ReallocAll opened this issue 2 years ago • 0 comments

Example:

#include <modloader/cutils.h>
#include <modloader/log.h>

THOOK(on_initialize_logging, void,
		"_ZN15DedicatedServer17initializeLoggingEv",
		uintptr_t this)
{
	on_initialize_logging.original(this);
	
	char array[32];  // sizeof(std::string) == 32
	void *sstr_new = NULL;
	void *sstr_array = array;
	void *sstr_malloc = malloc(32);

	std_string_string(&sstr_new, "Constructed using operator new allocated memory");
	std_string_string(&sstr_array, "Constructed using array allocated memory");
	std_string_string(&sstr_malloc, "Constructed using malloc allocated memory");

	// The block of memory returned by std_string_c_str will be freed after
	// the std::string object is destructed, use strdup to save it if needed!
	char *msg = strdup(std_string_c_str(sstr_new));

	modloader_logd("std::string", std_string_c_str(sstr_new));
	modloader_logd("std::string", std_string_c_str(sstr_array));
	modloader_logd("std::string", std_string_c_str(sstr_malloc));

	std_string_destroy(sstr_new, true);
	std_string_destroy(sstr_array, false);
	std_string_destroy(sstr_malloc, false);
	
	modloader_logw("std::string", msg); // print again
	free((void *)msg);
	free(sstr_malloc);
}

Out:

11:45:14 Debug [std::string] Constructed using operator new allocated memory
11:45:14 Debug [std::string] Constructed using array allocated memory
11:45:14 Debug [std::string] Constructed using malloc allocated memory
11:45:14 Warn  [std::string] Constructed using operator new allocated memory

ReallocAll avatar Sep 25 '23 17:09 ReallocAll