我想DllImport下面的函数。然而,"ret“返回true,但是我的字符串数组似乎是空的,所以我想我可能需要一些封送处理。任何小费都欢迎!(预先谢谢:)
C函数:
bool getBootLog(char **a1);下面的代码是用于测试的,不能正常工作。
DllImport:
[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());
}在以下方面的成果:
制备的bootLog..。引导日志长度:0引导日志:
发布于 2016-05-30 21:52:06
修改声明:
[DllImport("ext.dll", CharSet = CharSet.Ansi)]
public static extern bool getBootLog(ref IntPtr bootLogPtr);代码的编辑版本中的尝试行看起来不正确。
var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));实际上,应该指定缓冲区的大小。
var ptr = Marshal.AllocHGlobal(100); // Set it to 100 bytes, maximum!将长度写入ptr,因为它是C样式的以空结尾的字符串。
Marshal.WriteByte(ptr, 100, 0);然后调用我头顶上的电话:
IntPtr ptrBuf = ptr;
getBootLog(ref ptrBuf);通过ptrBuf将缓冲区的内容复制到字符串变量中:
string sBootLog = Marshal.PtrToStringAnsi(ptrBuf);清除非托管内存内容:
Marshal.FreeHGlobal(ptr);https://stackoverflow.com/questions/37531465
复制相似问题