我正在编写 C# 代码,并且有一段代码需要调用非托管 C++ 库。
库头的签名是这样的
bool GetValueFromFile(char* sPathToFile, char* &sResult);
我应该用 C# 翻译什么签名?我试过:
bool GetValueFromFile(string filePath, ref string result)
但它不起作用。无一异常(exception),返回值为真。但字符串结果保持为空。 out string result
或 StringBuilder result
也是一样。
我使用 Marshal.GetDelegateForFunctionPointer 获取函数指针作为委托(delegate)。
最佳答案
您可以像处理指向指针的指针一样处理对指针的引用,至少就 P/Invoke 而言是这样。
我认为您可能需要为 sResult
参数使用 IntPtr
,同时使用 Marshal.PtrToStringAnsi()
或 Marshal.PtrToStringAuto()
, 但如果不知道 C/C++ 函数是否分配了字符串内存,就很难说了。
如果有效,您可能仍需要使用 Marshal.FreeCoTaskMem()
释放内存(在 获取字符串之后)或 Marshal.FreeHGlobal()
,但是如果不知道 C/C++ 函数的作用,就不可能确定这一点。
注意:如果使用 IntPtr
获取输出值,您将需要使用 out result
或 ref result
。
关于c# - 我应该使用什么 C# 数据类型来与非托管类型 "char* &sResult"交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17291803/