亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# Pinvoke 字符串

C# Pinvoke 字符串

C#
牧羊人nacy 2022-10-23 13:24:30
我正在嘗試使用 PInvoke 綁定此 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 傳遞,但是當我嘗試使用它時它會因嘗試讀取或寫入受保護的內存而崩潰。
查看完整描述

1 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

我希望它應該是這樣的:


// 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;

}


查看完整回答
反對 回復 2022-10-23
  • 1 回答
  • 0 關注
  • 119 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號