- Home /
Returning variables in a plugin
Hey guys,
I've got this custom plugin I'm writing, and I've run into a bit of a snag.
//Plugin.m
const char* _TagForSource(const char *sender, const char *key){
return "Hello!";
}
//PluginHandler.cs
[DllImport("__Internal")]
private static extern string _TagForSource(string sender, string key);
public static string TagForSource(string sender, string key){
return _TagForSource(sender, key);
}
The problem I'm running into is that my app crashes whenever I call TagForSource, due to a malloc error(pointer was freed that wasn't malloc'd). Hardcoding the TagForSource in the PluginHandler to return a string doesn't throw an error, so I know that the problem is in Plugin.m - I just have no idea where I'm going wrong. What gives?
Answer by boat365 · Sep 06, 2011 at 02:08 PM
You should set the return type of your imported function to System.IntPtr instead of string, then return Marshal.PtrToStringAnsi(_TagForSource(sender, key)) from your TagForSource method.
edit: and here's the reason why- http://www.mono-project.com/Interop_with_Native_Libraries#Strings_as_Return_Values