C# PInvoke 输出字符串声明

发布于 2024-08-16 19:47:31 字数 531 浏览 6 评论 0原文

在 C# PInvoke 中,如何传递字符串缓冲区以便 C DLL 填充它并返回? PInvoke 声明是什么?

C 函数声明是

int GetData(char* data, int buflength);

在 C# 中,我已将其声明为

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

是否正确?我像这样传递 StringBuilder 变量

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

我想知道它是否正确?

谢谢

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)]StringBuilder 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回首观望 2024-08-23 19:47:31

我相信这是正确的。

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

它是这样调用的:

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

我曾经想对我的函数返回的字节有更多的控制,并这样做:

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

像这样使用:

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 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);
}
瑕疵 2024-08-23 19:47:31

我认为这里没有必要使用 MarshalAs 属性。 StringBuilder 是 char* 输出的正确选择。

我想添加 CharSet 属性会很好,因为您在这里处理字符串。

像这样:

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

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)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文