Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

parameters - C# PInvoke out strings 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)]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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...