gpt4 book ai didi

C# Pinvoke 字符串

转载 作者:行者123 更新时间:2023-11-30 22:55:38 26 4
gpt4 key购买 nike

我正在尝试使用 PInvoke 绑定(bind)此 C 函数。

bool GuiTextBox(Rectangle bounds, char *text, int textSize, bool editMode); 

这是 PInvoke 签名。

[DllImport(nativeLibName,CallingConvention = CallingConvention.Cdecl)]
public static extern bool GuiTextBox(Rectangle bounds,
string text,
int textSize,
bool freeEdit);

当我尝试使用它时,字符串没有被修改。我尝试将它作为 ref 传递,但当我尝试使用它时,它因尝试读取或写入 protected 内存而崩溃。

最佳答案

我希望它应该是这样的:

// private : do not expose inner details; 
// we have to manipulate with StringBuilder
[DllImport(nativeLibName,
CallingConvention = CallingConvention.Cdecl,
EntryPoint = "GuiTextBox",
CharSet = CharSet.Unicode)] //TODO: Provide the right encoding here
private static extern bool CoreGuiTextBox(Rectangle bounds,
StringBuilder text, // We allow editing it
int textSize,
bool freeEdit);

// Here (in the public method) we hide some low level details
// memory allocation, string manipulations etc.
public static bool CoreGuiTextBox(Rectangle bounds,
ref string text,
int textSize,
bool freeEdit) {
if (null == text)
return false; // or throw exception; or assign "" to text

StringBuilder sb = new StringBuilder(text);

// If we allow editing we should allocate enough size (Length) within StringBuilder
if (textSize > sb.Length)
sb.Length = textSize;

bool result = CoreGuiTextBox(bounds, sb, sb.Length, freeEdit);

// Back to string (StringBuilder can have been edited)
// You may want to add some logic here; e.g. trim trailing '\0'
text = sb.ToString();

return result;
}

关于C# Pinvoke 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55137825/

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