我从某人那里得到了这个程序集,我想在我的 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 和字符**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!