Problem at marshalling a standard C++ string to a C# string

假如想象 提交于 2019-12-11 13:25:32

问题


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 returns string pointers to all parameters.

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)

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

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 going wrong? How can I fix the C# method?


回答1:


Try changing the CharSet to CharSet = CharSet.Ansi




回答2:


Assuming those parameters are given to you from the application, why not simply use:

[DllImport(aDll.dll, CallingConvention = CallingConvention.Cdecl, 
    CharSet = CharSet.Auto)]
static unsafe extern uint aMethod(out string firstParameter, 
    out string secondParameter);

If you want them to go both ways, you could use a ref StringBuilder with a pre-allocated size (you should also use this if the C function expects you to manage your own memory -- you didn't say).



来源:https://stackoverflow.com/questions/7515798/problem-at-marshalling-a-standard-c-string-to-a-c-sharp-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!