c# - 将标准 C++ 字符串编码为 C# 字符串时出现问题

标签 c# .net c++ interop dllimport

我正在为管理 OCR 设备的 DLL 编写包装器。 DLL 有一个方法,其签名类似于以下内容:

unsigned long aMethod(char **firstParameter, char **secondParameter);

aMethod 返回指向所有参数的字符串指针。

我用 C# 写了这个签名...它几乎可以正常工作:

[DllImport(aDll.dll, CallingConvention = CallingConvention.Cdecl, 
    CharSet = CharSet.Auto)]
static unsafe extern ulong aMethod(ref IntPtr firstParameter, 
    ref IntPtr secondParameter);

我是这样调用的:

aMethod(ref firstParameter, ref secondParameter);

与字符串相关的编码和解码如下:

Marshal.PtrToStringAnsi(firstParameter)
Marshal.PtrToStringAnsi(secondParameter)

显然,此编码是根据 DLL 的 API 约定选择的。

现在,编码过程有问题。假设设备有一个带有这个字符串“abcdefg”的输入。如果我使用来自纯 C++ 代码的 DLL,我会得到“abcdefg”作为输出。但是,如果我使用我编写的 C# 签名,字符串会丢失其第一个字符,看起来像“bcdefg”。

出了什么问题?如何修复 C# 方法?

最佳答案

尝试更改 CharSetCharSet = CharSet.Ansi

关于c# - 将标准 C++ 字符串编码为 C# 字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7515798/

相关文章:

c# - 该类型必须是引用类型才能将其用作泛型类型或方法中的参数 'T'

c# - 在 DirectInput 应用程序中使用 SendInput API 模拟键盘

c# - 在 C# 中使用 json 对象

c# - 非 Windows 操作系统上的 .NET 框架 System.Windows.Form

c# - 数据库上没有事务的 SQL 错误 "uncommittable transaction is detected at the end of batch"

c# - 在 .net 核心应用程序中使用带有 MailKit 的 Html 模板发送电子邮件

c# - 日志记录仅在本地有效,但在部署到 Microsoft Azure 应用服务时无效

c++ - 使用 getifaddrs 获取 CAN 接口(interface)数据包统计信息

c++ - boost spirit 词素及其属性

c++ - 根据C++中的输入参数创建属于类的对象