C # calls a CPP function with an unknown number of arguments from CPP

I have a function in CPP with the following prototype:

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

i imports it from C # using the DLLImport attribute. questions: how to define a prototype in C # (in the DLLImport attribute)? how to pass arguments to this function? thank

+3
source share
2 answers

This is called the variational function. The P / Invoke support information is pretty scarce for them, that's what I found out.

I could not find a way to direct DllImportfunction with a variable number of arguments. I had DllImportall the options for arguments as different overloads.

Take wsprintf for example . It has the following prototype in winuser.h:

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

# :

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 :

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

, CPP . extern "C" __declspec (dllexport) char * myFunc (char *,...);

# DLLImport?

!

0

Source: https://habr.com/ru/post/1698434/


All Articles