我有一个来自 native 代码的示例函数
HRESULT getSampleFunctionValue(_Out_ LPWSTR * argument)
该函数输出参数中的值。我需要从托管代码调用它
[DllImport("MyDLL.dll", EntryPoint = "getSampleFunctionValue", CharSet = CharSet.Unicode)]
static extern uint getSampleFunctionValue([MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder argument);
这会返回垃圾值。 AFAIK 原始 C 函数不会使用 CoTaskMemAlloc 创建字符串。正确的调用是什么?
任何帮助将不胜感激。
最佳答案
您需要 C# 代码来接收指针。像这样:
[DllImport("MyDLL.dll")]
static extern uint getSampleFunctionValue(out IntPtr argument);
这样调用它:
IntPtr argument;
uint retval = getSampleFunctionValue(out argument);
// add a check of retval here
string argstr = Marshal.PtrToStringUni(argument);
然后您可能还需要调用 native 函数来释放它分配的内存。您可以在调用 Marshal.PtrToStringUni 之后立即执行此操作,因为此时您不再需要该指针。或者返回的字符串可能是静态分配的,我不能确定。无论如何, native 库的文档将解释需要什么。
您可能还需要指定调用约定。正如所写, native 函数看起来会使用 __cdecl
。但是,也许您没有在问题中包含 __stdcall
的规范。再次,请查阅 native 头文件以确定。
关于c# - 从 C 函数编码 LPWSTR *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18118978/