我想 DllImport 以下功能。尽管如此,“ret”返回真,但我的字符串数组似乎是空的,所以我想我可能需要一些封送处理。欢迎任何提示!提前致谢 :)
C函数:
bool getBootLog(char **a1);
下面的代码用于测试,不能正常工作。
DLL导入:
[DllImport("ext.dll")]
public static extern bool getBootLog(string[] bootLog);
当前代码:
string[] bootLog = new string[1024 * 1024];
bool ret = getBootLog(bootLog);
foreach (string s in bootLog)
{
Debug.WriteLine(s);
}
还有 2 次无效的尝试:
var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
try
{
getBootLog(out ptr);
var deref1 = (string)Marshal.PtrToStringAnsi(ptr);
Debug.WriteLine(deref1);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
var ptr2 = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
try
{
getBootLog(out ptr2);
var deref1 = (IntPtr)Marshal.PtrToStructure(ptr2, typeof(IntPtr));
var deref2 = (string[])Marshal.PtrToStructure(deref1, typeof(string[]));
Debug.WriteLine(deref2);
}
finally
{
Marshal.FreeHGlobal(ptr2);
}
莫森的想法:
[DllImport("Ext.dll")]
public static extern bool getBootLog(StringBuilder bootLog);
try
{
int bufferSize = 50;
StringBuilder bootLog = new StringBuilder(" ", bufferSize);
Debug.WriteLine("Prepared bootLog...");
getBootLog(bootLog);
Debug.WriteLine("Bootlog length: " + bootLog.Length);
string realString = bootLog.ToString();
Debug.WriteLine("Bootlog: " + realString);
}
catch(Exception ex)
{
Debug.WriteLine("Xception: " + ex.ToString());
}
结果是:
准备好的引导日志...引导日志长度:0 引导日志: