DllImport 和 char*
我有一个想要从 DLL 导入的方法,它的签名为:
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);
但都没有在 DriveLetter 变量中返回任何内容。
I have a method I want to import from a DLL and it has a signature of:
BOOL GetDriveLetter(OUT char* DriveLetter)
I've tried
[DllImport("mydll.dll")]
public static extern bool GetDriveLetter(byte[] DriveLetter);
and
[DllImport("mydll.dll")]
public static extern bool GetDriveLetter(StringBuilder DriveLetter);
but neither returned anything in the DriveLetter variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来函数
GetDriveLetter
需要一个char*
,它指向足够的内存来包含驱动器号。我认为解决此问题的最简单方法是传递原始
IntPtr
并将对GetDriveLetter
的调用包装在 API 中,该 API 负责资源管理和转换为 <代码>字符串。It appears the function
GetDriveLetter
is expecting achar*
which points to sufficient memory to contain the drive letter.I think the easiest way to approach this problem is to pass a raw
IntPtr
and wrap the calls toGetDriveLetter
in an API which takes care of the resource management and conversion to astring
.StringBuilder 可能是最佳选择,但您必须在调用函数之前设置字符串生成器的容量。由于 C# 不知道
GetDriveLeter
将使用多少内存,因此您必须确保 StringBuilder 有足够的空间。然后,编组器会将分配给该长度的 char* 传递给函数,并将其编组回 StringBuilder。有关示例,请参阅 p/invoke GetWindowText() 示例 。
The StringBuilder is probably the way to go, but you have to set the capacity of the string builder before calling the function. Since C# has no idea how much memory that
GetDriveLeter
will use, you must make sure the StringBuilder has enough space. The marshaller will then pass achar*
allocated to that length to the function and marhsall it back to the StringBuilder.See the p/invoke sample for GetWindowText(), for an example.
我遇到了一个相关的情况,该函数有一个 char * 参数,但我缺少 CharSet 赋值:
I had a related situation where the function had a
char *
parameter and I was missing theCharSet
assignment: