将标准c++字符串编组为c#字符串时出现的问题
Problem at marshalling a standard C++ string to a C# string
我正在为管理OCR设备的DLL编写包装器。DLL有一个签名如下的方法:
unsigned long aMethod(char **firstParameter, char **secondParameter);
方法返回指向所有参数的字符串指针。
我在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#方法?
尝试将CharSet
更改为CharSet = CharSet.Ansi
假设这些参数是应用程序提供给您的,为什么不直接使用:
[DllImport(aDll.dll, CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Auto)]
static unsafe extern uint aMethod(out string firstParameter,
out string secondParameter);
如果您希望它们双向运行,您可以使用预分配大小的ref StringBuilder
(如果C函数希望您管理自己的内存—您没有说—您也应该使用它)。
相关文章:
- setlocale的C++土耳其字符串问题
- C++字符串问题-如何访问字符串元素
- 提升,从字符串问题中获得时间
- 字符串问题中的系统( "command" ) 字符串
- 从文件和字符串问题中读取
- 将C++函数转换为 C#(字符串问题)
- 有关字符串C++问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- Dll导入Marshal C++字符串问题
- 崩溃:字符串问题
- 正在寻找另一种解决二进制字符串问题的尝试
- C++ Win32 是字符串问题
- 迭代器字符串问题
- Python 3:Python/C API字符串问题
- 带有空格的C++字符串问题
- 有些字符串问题
- C++11 std::regex_replace()创建带有特定字符串问题的regexp
- Turbo C++的字符串问题
- 棘手的子字符串问题