PInvoke error when sorting a structure with a string in it

I have a C ++ structure

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

and c # struct

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

C ++ library provides

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

And it is imported as

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

However, when I call this function, I get

MarshalDirectiveException was unhandled

The method type signature is not compatible with PInvoke.

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

+3
source share
1 answer

. IntPtr Marshal.PtrToStringAuto/Ansi/Uni, . , char*, PtrToStringAnsi.

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

Source: https://habr.com/ru/post/1714247/


All Articles