本文介绍了C# PInvoke out 字符串声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C# PInvoke 中,如何传递字符串缓冲区以便 C DLL 填充它并返回?PInvoke 声明是什么?
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?
C 函数声明是
int GetData(char* data, int buflength);
在 C# 中,我已将其声明为
In C#, I have declared it as
[DllImport(DllName)]
static extern Int32 GetData([MarshalAs(UnmanagedType.LPStr)]StringBuilder receiveddata, Int32 buflen);
正确吗?我像这样传递 StringBuilder 变量
Is it correct? I'm passing the StringBuilder variable like this
int bufferLength = 32;
StringBuilder data = new StringBuilder(bufferLength);
int result = GetData(data, bufferLength);
我想知道它是否正确?
谢谢
推荐答案
我认为是正确的.
[DllImport(DllName)]
static extern int GetData(StringBuilder data, int length);
是这样调用的:
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);
这样使用:
byte[] bytes = new byte[length];
fixed(byte* ptr = bytes)
{
bool success = Library.GetData(ptr, length);
if (!success)
Library.GetError();
return Encoding.UTF8.GetString(bytes);
}
这篇关于C# PInvoke out 字符串声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!