元帅"字符*"在C#元帅、字符、QUOT

2023-09-02 01:33:21 作者:給莪ー槍喊庝旳却媞妳

由于在DLL中下面的C函数:

Given the following C function in a DLL:

char * GetDir(char* path );

你会怎样的P / Invoke这个函数到C#和元帅的char *正常。 .NET似乎知道该怎么做LPCTSTR,但是当我想不出任何封送处理不会导致NotSupportedException异常调用这个函数的时候火。

How would you P/Invoke this function into C# and marshal the char * properly. .NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.

推荐答案

OregonGhost的答案是只有当字符*从GETDIR返回要么是分配HGLOBAL或LocalAlloc正确的。我不记得哪一个,但CLR会认为从PInvoke的函数的任何字符串返回类型被分配一个或另一个。

OregonGhost's answer is only correct if the char* returned from GetDir is either allocated in HGlobal or LocalAlloc. I can't remember which one but the CLR will assume that any string return type from a PInvoke function was allocated with one or the other.

一个更可靠的方法是键入GETDIR的回报是IntPtr的。然后你可以使用任何的Marshal.PtrToStringAnsi功能,以获得一个字符串类型。它也给你释放的字符串中您选择的方式届灵活性。

A more robust way is to type the return of GetDir to be IntPtr. Then you can use any of the Marshal.PtrToStringAnsi functions in order to get out a string type. It also gives you th flexibility of freeing the string in the manner of your choosing.


[DllImport("your.dll", CharSet = CharSet.Ansi)]
IntPtr GetDir(StringBuilder path);

您可以给我们任何其他线索,以GETDIR的行为?它修改输入字符串?如何这是返回的值分配呢?如果你能提供,我可以给一个更好的答案。

Can you give us any other hints as to the behavior of GetDir? Does it modify the input string? How is the value which is returned allocated? If you can provide that I can give a much better answer.