簡體   English   中英

C#使用CPP中未知數量的args調用CPP函數

[英]C# invoking CPP function with unknown number of args from CPP

我在CPP中有一個函數,具有以下原型:

char* complexFunction(char* arg1, ...);

我使用DLLImport屬性從C#導入它。 問題是:我如何在C#中定義原型(在DLLImport屬性下)? 我如何將參數傳遞給這個函數? 謝謝

這稱為可變函數。 P / Invoke對它們的支持信息相當稀缺,這就是我發現的。

我找不到直接DllImport一個具有可變數量參數的函數的方法。 我不得不將所有參數變量DllImport作為不同的重載。

我們以wsprintf為例 它在winuser.h有以下原型:

int WINAPIV wsprintf(      
    LPTSTR lpOut,
    LPCTSTR lpFmt,
    ...);

它可以在C#中使用,如下所示:

using System;
using System.Text;
using System.Runtime.InteropServices;

class C {

  // first overload - varargs list is single int
  [DllImport("user32.dll", CallingConvention=CallingConvention.Cdecl)]
  static extern int wsprintf(
    [Out] StringBuilder buffer,
    string format,
    int arg);

  // second overload - varargs list is (int, string)
  [DllImport("user32.dll", CallingConvention=CallingConvention.Cdecl)]
  static extern int wsprintf(
    [Out] StringBuilder buffer,
    string format,
    int arg1,
    string arg2);

  public static void Main() {
    StringBuilder buffer = new StringBuilder();
    int result = wsprintf(buffer, "%d + %s", 42, "eggs!");
    Console.WriteLine("result: {0}\n{1}", result, buffer);
  }
}

現在來解決你的complexFunction

char* complexFunction(char* arg1, ...);

它的varargs列表應該以相同的方式解決:提供所有有用的重載。 但是還有另一種並發症 - 返回類型。 我假設complexFunction分配並返回char數組。 在這種情況下,調用者最有可能負責數組的釋放。 為了實現這一點,您還應該導入釋放例程,讓我們將其稱為void free(void*)

假設已經假定所有這些,使用complexFunction C#代碼將如下所示:

using System;
using System.Text;
using System.Runtime.InteropServices;

class C {

  [DllImport("your.dll",
             CallingConvention=CallingConvention.Cdecl,
             CharSet=CharSet.Ansi)]
  static extern IntPtr complexFunction(
    string format,
    int arg1, int arg2);

  [DllImport("your.dll", CallingConvention=CallingConvention.Cdecl)]
  static extern void free(IntPtr p);

  public static void Main() {
    IntPtr pResult = complexFunction("%d > %s", 2, 1);
    string sResult = Marshal.PtrToStringAnsi(pResult);
    free(pResult);
    Console.WriteLine("result: {0}", sResult);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM