Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible interop memory leak when passing temporary strings from native to managed #43

Open
MuffinTastic opened this issue Jan 30, 2023 · 0 comments

Comments

@MuffinTastic
Copy link
Contributor

In Host engine.h, a new C string is allocated like so:

GENERATE_BINDINGS inline const char* GetProjectPath()
{
	std::string str = EngineProperties::LoadedProject.GetValue();

	// Copy string so we can use it out-of-scope
	char* cstr = new char[str.length() + 1];
	strcpy_s( cstr, str.length() + 1, str.c_str() );
		
	return cstr;
};

In the generated interop code on the managed side it's then converted to a C# string by use of MemoryContext:

public static string GetProjectPath(  ) 
{
	using var ctx = new MemoryContext( "Engine.GetProjectPath" );
	return ctx.GetString( _GetProjectPath(  ) );
}

MemoryContext.GetString() is defined as such:

internal string GetString( IntPtr strPtr )
{
	return Marshal.PtrToStringUTF8( strPtr ) ?? "UNKNOWN";
}

Marshal.PtrToStringUTF8()'s description says:

Allocates a managed String and copies all characters up to the first null character from an unmanaged UTF-8 string into it.

I don't see where cstr gets deallocated in this chain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants