gpt4 book ai didi

c# - C# 中等效的 LPCSTR 数据类型

转载 作者:太空狗 更新时间:2023-10-30 00:03:04 25 4
gpt4 key购买 nike

我有一个接受三个参数的 API:

HANDLE  Connect(LPCSTR MachineName, LPCSTR ServerName, BOOL EnableDLLBuffering); 

如何在 C# 中使用此方法?

LPCSTR 的等价物是什么?应该使用什么来代替 HANDLE

最佳答案

HANDLE 等效项是 IntPtr(或者您可以使用 SafeHandle 的子类之一,其中许多定义在命名空间 Microsoft.Win32.SafeHandles)。 LPCSTR 的等效项是 stringStringBuilder(但 string 更好,因为您将字符串传递给方法和方法不会修改它)。您甚至可以使用 byte[](正如我在其他回复中写给您的那样,但您必须在缓冲区中对字符串进行编码,并在完了……挺不方便的)。最后,LPCSTR 是方法不会修改的常量 LPSTR。最好像其他响应一样设置 CharSet.Ansi

[DllImport("YourDll.dll", CharSet = CharSet.Ansi)]
static extern IntPtr Connect(string machineName, string serverName, bool enableDLLBuffering);

你称它为:

IntPtr ptr = Connect("MyMachine", "MyServer", true);

或者,如果您真的想自己进行编码:

[DllImport("YourDll.dll", CharSet = CharSet.Ansi)]
static extern IntPtr Connect(byte[] machineName, byte[] serverName, bool enableDLLBuffering);

public static byte[] GetBytesFromStringWithZero(Encoding encoding, string str)
{
int len = encoding.GetByteCount(str);

// Here we leave a "space" for the ending \0
// Note the trick to discover the length of the \0 in the encoding:
// It could be 1 (for Ansi, Utf8, ...), 2 (for Unicode, UnicodeBE), 4 (for UTF32)
// We simply ask the encoder how long it would be to encode it :-)
byte[] bytes = new byte[len + encoding.GetByteCount("\0")];
encoding.GetBytes(str, 0, str.Length, bytes, 0);
return bytes;
}

IntPtr ptr = Connect(
GetBytesFromStringWithZero(Encoding.Default, "MyMachine"),
GetBytesFromStringWithZero(Encoding.Default, "MyServer"),
true);

如果您必须始终使用相同的字符串多次调用该方法,则此变体更好,因为您可以缓存字符串的编码版本并获得一些速度(是的,通常这是无用的优化)

关于c# - C# 中等效的 LPCSTR 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18074655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com