如果此函数分配内存并让调用者负责释放它,恐怕您将不得不手动管理:将参数声明为 aref IntPtr
并使用Marshal
类的方法获取带有指向数据副本的 String .
然后调用适当的函数来释放内存(正如 Dirk 所说,如果没有关于该函数的更多信息,我们无法对此进行更多说明)。
如果它真的必须在调用之前分配,它应该是这样的:
[DllImport("yourfile.dll", CharSet = CharSet.Ansi)]
public static extern sbyte service_GetParameter ( String parameter, Int32 length, ref IntPtr val);
public static string ServiceGetParameter(string parameter, int maxLength)
{
string ret = null;
IntPtr buf = Marshal.AllocCoTaskMem(maxLength+1);
try
{
Marshal.WriteByte(buf, maxLength, 0); //Ensure there will be a null byte after call
IntPtr buf2 = buf;
service_GetParameter(parameter, maxLength, ref buf2);
System.Diagnostics.Debug.Assert(buf == buf2, "The C++ function modified the pointer, it wasn't supposed to do that!");
ret = Marshal.PtrToStringAnsi(buf);
}
finally { Marshal.FreeCoTaskMem(buf); }
return ret;
}