PInvoke and char**(PInvoke 和字符**)
问题描述
我从某人那里得到了这个程序集,我想在我的 c# 应用程序中使用它.
I got this assembly from someone which I'd like to use in my c# application.
标题如下所示:
int __declspec(dllimport) s2o(WCHAR* filename, char** out, int* len);
我设法让它部分工作,使用:
I managed to get it partly working, using:
[DllImport("s2o.dll", EntryPoint = "?skn2obj@@YAHPA_WPAPADPAH@Z", CallingConvention = CallingConvention.Cdecl)]
public static extern int s2o(
[MarshalAs(UnmanagedType.LPWStr)]
string filename,
ref char[] @out,
ref int len
);
然后这样称呼它:
char[] result = null;
int length = 0;
s2o("filepath", ref result, ref length);
它似乎部分起作用,因为长度"实际上得到了一个值.不幸的是,结果"保持为空.
It seems to work partly, because 'length' actually gets a value. Unfortunatly, 'result' stays null.
我应该怎么做才能让它工作?
What should I do to get this working?
好的,我设法开始工作,将 char[] 替换为 IntPtr,然后像 Nick 建议的那样调用Marshal.PtrToStringAnsi":
Ok I managed to get to to work by replacing the char[] with a IntPtr and then calling 'Marshal.PtrToStringAnsi' like Nick suggested:
string result = Marshal.PtrToStringAnsi(ptr);
但是,由于同一答案中的评论,我有点担心内存使用情况.程序集中没有提供其他方法,所以我该如何清理?
However, because of the comments in that same answer I'm a little worried about memory usage. There are no other methods provided in the assembly so how can I clear things up?
推荐答案
看看 Marshal.PtrToStringAnsi 方法.
或者正如 Centro 在对您问题的评论中所说,PtrToStringAuto 可能更合适.
Or as Centro says in the comment to your question, PtrToStringAuto may be more appropriate.
复制所有字符直到第一个来自非托管 ANSI 的空字符字符串到托管字符串,并加宽每个 ANSI 字符转换为 Unicode.
Copies all characters up to the first null character from an unmanaged ANSI string to a managed String, and widens each ANSI character to Unicode.
另请注意,您可能负责释放从该函数返回的内存.
Also note that you may be responsible for freeing the memory returned from this function.
这篇关于PInvoke 和字符**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PInvoke 和字符**


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01