在编组标准的C ++字符串到C#字符串问题字符串、标准、问题

2023-09-06 19:09:58 作者:牙齿晒太阳

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

I'm writing a wrapper for a DLL that manages an OCR device. The DLL has a method whose signature resembles the following:

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

返回amethod方法字符串指针所有参数。

aMethod returns string pointers to all parameters.

我写了 C#这个签名......这几乎是功能:

I wrote this signature in C#... it is almost functional:

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

我做的调用以这种方式:

I do the invocation in this way:

aMethod(ref firstParameter, ref secondParameter);

编组和解组相关的字符串做如下:

Marshalling and unmarshalling related to the strings is done as here:

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

显然,这个编组是基于DLL的API约定选择。

Obviously, this marshalling has been selected based on DLL's API conventions.

现在,编组过程有问题。假设该设备具有输入以该字符串ABCDEFG。如果我使用纯C ++ code中的DLL我得到ABCDEFG作为输出。但是,如果我使用C#签名从来就wroted,字符串失去了它的第一个字符,看起来像bcdefg。

Now, the marshalling process has a problem. Suppose that the device has an input with this string "abcdefg". If I use the DLL from pure C++ code I get "abcdefg" as an output. But, if I use the C# signature I´ve wroted, the string loses its first character and looks like "bcdefg".

What's回事?如何解决C#的方法是什么?

What´s going wrong? How can I fix the C# method?

推荐答案

试着改变 字符集字符集= CharSet.Ansi