PInvoke error when marshalling struct with a string in it

匆匆过客 提交于 2019-12-18 09:00:36

问题


I have a C++ struct

struct UnmanagedStruct
{
   char* s;
   // Other members
};

and a C# struct

struct ManagedStruct {
   [MarshalAs(UnmanagedType.LPStr)]
   string s;
   // Other members
}

the C++ library exposes

extern "C" UnmanagedStruct __declspec(dllexport) foo( char* input );

And it is imported like

  [DllImport("SomeDLL.dll", CharSet = CharSet.Ansi)]
  static extern ManagedStruct foo( string input );

However when I call this function I get

MarshalDirectiveException was unhandled

Method's type signature is not PInvoke compatible.

The thing is, this function call works if I remove the char* s and the string s from the structs.


回答1:


For this type of scenario, do not use a String directly. Instead switch the type to be an IntPtr value and use Marshal.PtrToStringAuto/Ansi/Uni as appropriate. In this case, since your native code uses char*, PtrToStringAnsi is the best choice.

struct ManagedStruct {
  IntPtr s;
  public string sAsString { get { return Marshal.PtrToStringAnsi(s); } }
}


来源:https://stackoverflow.com/questions/1223690/pinvoke-error-when-marshalling-struct-with-a-string-in-it

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