如何从非托管C++ dll 字符**转换为 C# 字符串并返回

How do I convert from an unmanaged C++ dll char** to a C# string and back

本文关键字:字符 转换 字符串 返回 串并 dll C++      更新时间:2023-10-16

我正在尝试在非托管C++ DLL 上调用函数,搜索我接近的堆栈溢出帖子,但我无法让它完全工作。

在 .h 文件中声明如下:

extern int SomeDLLMethod(const char **data, int *count);

数据是一个字符串

我在 C# 中声明如下:

[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int SomeDLLMethod(IntPtr data, ref int count);

然后我可以从 C# 调用它,如下所示:

unsafe
{
    fixed (byte* buffer = new byte[MAX_LENGTH])
    {
        IntPtr ptr = new IntPtr(buffer);
        int count = 0;
        var retVal = SomeDLLMethod(ptr, ref count);
        var dataString = Marshal.PtrToStringAuto(ptr);
        Console.WriteLine(dataString);
     }
 }

调用成功,缓冲区中有一个计数和数据,但我如何将此值读回 C# 字符串?

元帅的方法给了我垃圾

问题中没有足够的信息来 100% 确定,但我的猜测是你需要这个:

[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int SomeDLLMethod(ref IntPtr data, ref int count);
.....
IntPtr data;
int count;
int retval = SomeDLLMethod(ref data, ref count);
string str = Marshal.PtrToStringAnsi(data, count);

理想情况下,在提出这样的问题时,您应该包含本机函数的完整文档。我这样说是因为字符**可以意味着许多不同的事情。

我的假设是,这里的 char** 是指向 DLL 分配的以 null 结尾的 C 字符串的指针。您的代码假设调用方分配缓冲区,但如果是这样,那么我希望看到 char* 而不是 char**。