I would like to import a function like this:
我期望实现如下导入函数:
[return: MarshalAs(UnmanagedType.LPWStr)]
[DllImport("DLL.dll", EntryPoint="FuncUtf16", ExactSpelling=true, PreserveSig=true, CharSet=CharSet.Unicode)]
public static extern string Func();
But this gives me an error like this:
但应用软件给出如下错误:
"Windows has triggered a breakpoint in Test.exe. This may be due to a corruption of the heap, which indicates a bug in Test.exe or any of the DLLs it has loaded. "
And when I press “Continue” repeatedly, the function does give the expected output. However, when I chance the above declaration to:
当我按"Continue"循环后,函数给给出异常输出。然后,当我将上述导入函数声明修改:
[DllImport("DLL.dll", EntryPoint="FuncUtf16", ExactSpelling=true, PreserveSig=true, CharSet=CharSet.Unicode)]
public static extern IntPtr Func();
(changing the return type to IntPtr) and call it as follows:
(改变返回值为IntPtr
)执行如下代码调用:
Dim a As IntPtr = Func()
Dim Str As String = Runtime.InteropServices.Marshal.PtrToStringUni(a)
, I get no errors and it works perfectly fine! Whats wrong with using the “MarshalAs” way of declaring a function in a dll?
, 软件无错误并工作正常! 使用MarshalAs
声明DLL函数有什么错误?
最佳答案:
Writing the PInvoke signature for a method which returns a char*
/ wchar_t*
requires a lot of care because the CLR special cases string return types. It makes the following assumptions
写PInvoke
签名返回值为char*
/wchar_t*
时需要特别注意,因为CLR
的特殊返回值类型时做如下假定:
- The memory for the
char*
must be freed after converting to string - The memory was allocated with
CoTaskMemAlloc
If either of these aren’t true (usually the case) then the program will run into errors.
In general it’s best to simply return an IntPtr
and manually marshal the string as you’ve done with PtrToStringUni
.