如何从非托管C++ dll 字符**转换为 C# 字符串并返回
How do I convert from an unmanaged C++ dll char** to a C# string and back
我正在尝试在非托管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**。
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 字符转换功能 std::isupper() & std::islower() C++17
- 将字符 * 转换为字符串 *
- 在编译时将常量字符* 转换为常量 char_type*
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 无法使用字符串流将字符转换为字符串C++
- 将无符号字符 C++ 转换为 C#
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法<string>从"常量字符 []"转换为<类名>
- 不能将字符转换为整数吗?
- 编译时将字符*转换为字节
- CP1251:从字符* 转换为 wchar_t* 时的编码失真
- 将单个字符转换为 std::string 前缀 \x01
- PPM 将字符转换为 int 授予负数
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 将常量字符* 转换为字符时出错