c#中如何使用DLL导出字符串指针

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.

参考网址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值