的DllImport与char * [英] DllImport and char*
本文介绍了的DllImport与char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法,我想从一个DLL导入和它的签名:
I have a method I want to import from a DLL and it has a signature of:
BOOL GetDriveLetter(OUT char* DriveLetter)
我试过
[DllImport("mydll.dll")]
public static extern bool GetDriveLetter(byte[] DriveLetter);
和
[DllImport("mydll.dll")]
public static extern bool GetDriveLetter(StringBuilder DriveLetter);
但无论返回的驱动器号变任何东西。
but neither returned anything in the DriveLetter variable.
推荐答案
它看起来像函数 GetDriveLetter
期待一个的char *
指向足够的内存来容纳的驱动器盘符。
It looks like the function GetDriveLetter
is expecting a char*
which points to sufficient memory to contain the drive letter.
我觉得要解决这个问题最简单的方法是通过一个原始的的IntPtr
,敷调用 GetDriveLetter
在API,它负责资源管理和转换到字符串
。
I think the easiest way to approach this problem is to pass a raw IntPtr
and wrap the calls to GetDriveLetter
in an API which takes care of the resource management and conversion to a string
.
[return:MarshalAsAttribute(UnmanagedType.Bool)]
private static extern bool GetDriveLetter(IntPtr ptr);
public static bool GetDriveLetter(out string drive) {
drive = null;
var ptr = Marshal.AllocHGlobal(10);
try {
var ret = GetDriveLitter(ptr);
if ( ret ) {
drive = Marshal.PtrToStringAnsi(ptr);
}
return ret;
} finally {
Marshal.FreeHGlobal(ptr);
}
}
这篇关于的DllImport与char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文