c# - How can I marshal a Delphi short string using p/invoke? -


i have problem variable type dll importing in c#. written in object oriented pascal , says developed delphi development tool.

on manual of library says shortstring packed array of bytes. first byte length , following exaclty 255 bytes string data need.

so after importing dll in c# wrote:

[return: marshalas(unmanagedtype.lparray)] 

then called function dll:

public static extern byte[] xxxx(); 

but getting following error:

cannot marshal 'return value': invalid managed/unmanaged type combination

on other hand tried following:

[return: marshalas(unmanagedtype.safearray)] 

this time error:

safearray of rank 18727 has been passed method expecting array of rank 1

can please tell me doing wrong, , firstly correct shortstring compiled library?

regards

i think cleanest way marshal delphi short string wrap in struct.

[structlayout(layoutkind.sequential)] public struct delphishortstring {     private byte length;      [marshalas(unmanagedtype.byvalarray, sizeconst=255)]     private byte[] payload;      public string value      {                  {              return encoding.default.getstring(payload, 0, length);          }         set          {             length = (byte)math.min(value.length, 255);             payload = encoding.default.getbytes(value.substring(0, length));         }     } } 

this type not blittable , cannot used function return value. if have control of delphi code, can ensure don't use short strings function return types. however, suspect don't have control of it. in case you'd need blittable version of struct. this:

[structlayout(layoutkind.sequential)] public unsafe struct delphishortstring {     private byte length;      private fixed byte payload[255];      public string value      {                  {             {                 byte[] bytes = new byte[length];                 fixed (byte* ptr = payload)                 {                     marshal.copy((intptr)ptr, bytes, 0, length);                 }                 return encoding.default.getstring(bytes, 0, length);              }         }         set          {             byte[] bytes = encoding.default.getbytes(value);             length = (byte)math.min(bytes.length, 255);             fixed (byte* ptr = payload)             {                 marshal.copy(bytes, 0, (intptr)ptr, length);             }         }     } } 

it indicative of poor design dll export delphi short string. suggests author of library has not designed compatible other compilers. in turn suggests functions may use default delphi calling convention. register , not supported microsoft tools. if hunch right, dll cannot consumed directly. need write adapter dll exposed more interop friendly interface.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -