简体   繁体   English

C#PInvoke out字符串声明

[英]C# PInvoke out strings declaration

In C# PInvoke, how do I pass a string buffer so that the C DLL fills it and returns? 在C#PInvoke中,如何传递字符串缓冲区以便C DLL填充它并返回? What will be the PInvoke declaration? PInvoke宣言是什么?

The C function declaration is C函数声明是

int GetData(char* data, int buflength);

In C#, I have declared it as 在C#中,我已将其声明为

[DllImport(DllName)]
static extern Int32 GetData([MarshalAs(UnmanagedType.LPStr)]StringBuilder receiveddata, Int32 buflen);

Is it correct? 这是对的吗? I'm passing the StringBuilder variable like this 我像这样传递StringBuilder变量

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. 我不认为在这里使用MarshalAs属性是必要的。 StringBuilder is a right choice for char* out. StringBuilder是char * out的正确选择。

I guess it will be good to add the CharSet property since you are dealing with strings here. 我想添加CharSet属性会很好,因为你在这里处理字符串。

Like this: 像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM