开发者

C# PInvoke out strings declaration

开发者 https://www.devze.com 2022-12-15 03:16 出处:网络
In C# PInvoke, how do I pass a string buffer so that the C DLL fills it and returns? What will be the PInvoke declaration?

In C# PInvoke, how do I pass a string buffer so that the C DLL fills it and returns? What will be the PInvoke declaration?

The C function declaration is

int GetData(char* data, int buflength);

In C#, I have declared it as

[DllImport(DllName)]
static extern Int32 GetData([MarshalAs(UnmanagedType.LPStr)]S开发者_Python百科tringBuilder receiveddata, Int32 buflen);

Is it correct? I'm passing the StringBuilder variable like this

int bufferLength = 32;
StringBuilder data = new StringBuilder(bufferLength);
int result = GetData(data, bufferLength);

I would like to know is it correct or not?

Thanks


I believe it's correct.

[DllImport(DllName)]
static extern int GetData(StringBuilder data, int length);

which is called like this:

StringBuilder data = new StringBuilder(32);
GetData(data, data.Capacity);

I once wanted to have more control over the bytes returned by my function and did it like this:

[DllImport(DllName)]
private unsafe static bool GetData(byte* data, int length);

used like this:

byte[] bytes = new byte[length];

fixed(byte* ptr = bytes)
{
  bool success = Library.GetData(ptr, length);

  if (!success)
    Library.GetError();

  return Encoding.UTF8.GetString(bytes);
}


I don't think that using MarshalAs attribute necessary here. StringBuilder is a right choice for char* out.

I guess it will be good to add the CharSet property since you are dealing with strings here.

Like this:

[DllImport(DllName, CharSet=CharSet.Auto)]
0

精彩评论

暂无评论...
验证码 换一张
取 消