的PInvoke和焦炭**

的PInvoke和焦炭**

问题描述:

我是一个完整的noob当涉及到C / C ++和PInvoke的,所以请裸跟我来。

I am a complete noob when it comes to c/c++ and PInvoke, so please bare with me.

我得到这个组件从别人,我想在我的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
);

,然后调用它是这样的:

And then calling it like this:

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?

编辑:

好,我设法通过与一个IntPtr的取代的char [],然后调用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 方法。

或者是中心的说,在评论你的问题,的PtrToStringAuto可能更合适。

Or as Centro says in the comment to your question, PtrToStringAuto may be more appropriate.

将所有字符,直到达到第一   从非托管ANSI空字符   字符串到托管String,并扩大   每个ANSI字符统一code。

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.