【发布时间】:2011-01-04 16:15:40
【问题描述】:
我正在与采用char**(即指向字符串的指针)的代码交互:
int DoSomething(Whatever* handle, char** error);
基本上,它需要一个句柄来处理它的状态,如果出现问题,它会返回一个错误代码和可选的错误消息(内存是在外部分配的,并通过第二个函数释放。那部分我已经弄清楚了: ) )。
但是,我不确定如何在 C# 中处理。我目前拥有的:
[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
private static unsafe extern int DoSomething(IntPtr handle, byte** error);
public static unsafe int DoSomething(IntPtr handle, out string error) {
byte* buff;
int ret = DoSomething(handle, &buff);
if(buff != 0) {
// ???
} else {
error = "";
}
return ret;
}
我翻来覆去,不知道怎么把它变成byte[],适合喂给UTF8Encoding.UTF8.GetString()
我走对了吗?
编辑:更明确地说,库函数分配内存,必须通过调用另一个库函数来释放内存。如果一个解决方案没有给我留下一个我可以释放的指针,那么这个解决方案是不可接受的。
额外问题:如上所述,该库使用 UTF-8 作为其字符串。我需要在我的 P/Invokes 中做任何特别的事情,还是只使用 string 来处理普通的 const char* 参数?
【问题讨论】:
-
你试过
out StringBuilder吗? -
我添加了一个额外的编辑来澄清根本问题。
标签: c# c string pinvoke marshalling